FormalRV

LatticeSurgery 461 declarations in 20 modules

FormalRV.LatticeSurgery.LDPCSurgery

FormalRV/LatticeSurgery/LDPCSurgery.lean
FormalRV.Framework.LDPCSurgery — LDPC lattice surgery gadget structure and structural verifier. Implements qianxu (Cain–Xu et al. 2026) Appendix C, especially Sec. C.1 ("Description"). A surgery gadget on a qLDPC code performs a single logical-Pauli-product measurement (PPM) by: (1) Initialising an ancilla system A in |0⟩. (2) Measuring τ_s cycles of merged-code stabilisers — the joint stabilisers of the data code Q and ancilla code A, coupled via connection matrices f_X' and f_Z. (3) Detaching A from Q by measuring A in the Z basis with adaptive Pauli corrections. The merged code's parity-check matrices are H̃_X = [ H_X 0 ] H̃_Z = [ H_Z f_Z ] [ f_X' H_X' ] [ 0 H_Z' ] Per the paper, the surgery gadget is fault-tolerant iff: (i) The merged code has distance d̃ = Θ(d_data). (ii) The merged code remains qLDPC. (iii) τ_s = Θ(d_data) (we use τ_s ≥ ⌈2 d_data / 3⌉). Plus the structural constraint that the target logical operator P̄ lies in the row span of H̃_X (X-type PPM) or H̃_Z (Z-type PPM): ⟨ℒ⟩ = f_X'ᵀ · ker(H_X'ᵀ) is restated here as a row-span identity on the merged matrix, which the implementer supplies a witness for. We accept (i) — the merged-code distance — as implementer- supplied (paper-cited from QDistRnd numerical computation). We verify (ii) and (iii) structurally; we verify the row-span identity (the kernel condition) decidably. ## Single-qubit vs multi-block PPMs This file handles the SINGLE-CODE-BLOCK case (one data code + one ancilla system). For PPMs across two code blocks (e.g., Z̄_i ⊗ Z̄'_j with i on memory, j on processor), use the bridge construction in `LDPCSurgeryBridge.lean`.
structureSurgeryGadget
structure SurgeryGadget
A single-code-block surgery gadget realising one logical Pauli measurement on a qLDPC data code. Per qianxu App. C.1, the implementer supplies: `data_code` — the data code Q(Q, S_X, S_Z), with parity matrices H_X = `data_code.hx`, H_Z = `data_code.hz`. `ancilla_n` — the number of ancilla qubits |Q'|. `ancilla_hx` — H_X', the ancilla X-check matrix (|S_X'| × ancilla_n). `ancilla_hz` — H_Z', the ancilla Z-check matrix (|S_Z'| × ancilla_n). `conn_x` — f_X', the connection matrix joining each ancilla X-check to a subset of data qubits (|S_X'| × data_code.n). `conn_z` — f_Z, the connection matrix joining each data Z-check to a subset of ancilla qubits (|S_Z| × ancilla_n). `tau_s` — number of merged-code measurement cycles (the surgery cycle count). `target_pauli` — the logical Pauli operator P̄ being measured, as a Bool vector of length `data_code.n + ancilla_n`. The vector's first `data_code.n` entries describe the action on Q; the remainder describes the action on Q'. `span_witness` — a Bool vector selecting which rows of the merged X- or Z-check matrix sum (XOR) to give the `target_pauli`. This is the row-span witness the framework uses to verify the kernel condition of qianxu Sec. C.1. `merged_qldpc_bound` — the qLDPC degree bound (Δ) that the implementer claims for the merged code. Verified structurally by `is_qldpc`.
defmerged_n
def merged_n (g : SurgeryGadget) : Nat
Total qubit count of the merged code = `data_code.n + ancilla_n`.
defmerged_hx
def merged_hx (g : SurgeryGadget) : BoolMat
Merged X-check matrix: H̃_X = [ H_X 0 ] [ f_X' H_X' ] The top block is the data X-checks extended by zeros on the ancilla qubits; the bottom block is the ancilla X-checks `H_X'` augmented by `f_X'` on the data qubits.
defmerged_hz
def merged_hz (g : SurgeryGadget) : BoolMat
Merged Z-check matrix: H̃_Z = [ H_Z f_Z ] [ 0 H_Z' ]
defdimensions_consistent
def dimensions_consistent (g : SurgeryGadget) : Bool
All matrix dimensions and row lengths are mutually consistent. Decidable.
deftargets_logical_correctly
def targets_logical_correctly (g : SurgeryGadget) : Bool
Structural correctness: the target logical Pauli operator equals the GF(2) sum of the rows of merged_hx selected by span_witness. This is the qianxu kernel-condition `⟨ℒ⟩ = f_X'ᵀ · ker(H_X'ᵀ)` restated as a row-span identity over the MERGED matrix, decidable on concrete instances.
deftau_s_sufficient
def tau_s_sufficient (g : SurgeryGadget) : Bool
Criterion (iii): `τ_s = Θ(d_data)`. We require `3 · τ_s ≥ 2 · d_data` (i.e., `τ_s ≥ ⌈2d/3⌉`), matching the paper's choice of `τ_s ≈ 2d/3` which balances space-like and time-like logical error rates.
defmerged_is_qldpc
def merged_is_qldpc (g : SurgeryGadget) : Bool
Criterion (ii): the merged code remains qLDPC, i.e., row and column weights of `merged_hx` and `merged_hz` are bounded by the claimed `merged_qldpc_bound`.
defverify_surgery_gadget
def verify_surgery_gadget (g : SurgeryGadget) : Bool
*The headline structural verifier** for a surgery gadget. Checks (decidably): dimensions are mutually consistent the merged code is qLDPC (criterion ii) τ_s is sufficient (criterion iii) the target logical lies in the row span of merged_hx (the kernel condition). Criterion (i) — merged-code distance d̃ = Θ(d_data) — is paper-cited from QDistRnd / Monte Carlo; we accept it as an implementer-supplied claim.
defverify_surgery_schedule
def verify_surgery_schedule (gadgets : List SurgeryGadget) : Bool
Every gadget in a list passes the headline verifier.

FormalRV.LatticeSurgery.LaSsynthImport

FormalRV/LatticeSurgery/LaSsynthImport.lean
FormalRV.LatticeSurgery.LaSsynthImport — SAT-synthesized lattice surgeries (Tan, Niu & Gidney, "A SAT Scalpel for Lattice Surgery", ISCA 2024) imported into our ZX/PPM IR by `PyCircuits/lasre_to_ppm.py`. Each design's `.lasre.json` (the *optimized*, minimum-spacetime-volume LaS that LaSsynth's SAT solver produces) is parsed into a `ZXDiagram`: every Z/X cube-spider becomes a Pauli-product MEASUREMENT (`mkSpider`). This is the user's thesis — "all lattice surgery, even optimized, goes through PPM" — applied to REAL optimizer output: the synthesized design is, in our framework, a PPM program. Correctness is certified externally by stimzx (`verify_stabilizers_stimzx = True`, see `PyCircuits/lasre_verify.py`), whose algorithm interprets every spider as a postselected parity measurement — identical to our `zxToPPM`. `factory121` is a PURE measurement fragment (0 H domain-walls), so its import is fully faithful; `majority_gate` additionally has 6 H domain-walls (basis changes), recorded separately for the faithful replay. GENERATED — do not edit by hand. No `sorry`, no `axiom`.
deffactory121_zx
def factory121_zx : ZXDiagram
ZXDiagram of the SAT-synthesized `factory121` lattice surgery (LaSsynth), imported by `PyCircuits/lasre_to_ppm.py`. 97 Z/X measurement spiders over 132 edge-qubits.
example(example)
example : factory121_zx.length = 97
The optimized `factory121` imported as 97 Pauli-product measurements (every spider is a PPM), and the ZX→PPM translation yields exactly one measurement per spider.
example(example)
example : (zxToPPM factory121_zx).length = factory121_zx.length
defmajority_gate_zx
def majority_gate_zx : ZXDiagram
ZXDiagram of the SAT-synthesized `majority_gate` lattice surgery (LaSsynth), imported by `PyCircuits/lasre_to_ppm.py`. 43 Z/X measurement spiders over 58 edge-qubits.
defmajority_gate_hwalls
def majority_gate_hwalls : List (List Nat)
`majority_gate` H domain-walls (basis-change nodes), each over its incident edge-qubits.
example(example)
example : majority_gate_zx.length = 43
The optimized `majority_gate` imported as 43 Pauli-product measurements (every spider is a PPM), and the ZX→PPM translation yields exactly one measurement per spider.
example(example)
example : (zxToPPM majority_gate_zx).length = majority_gate_zx.length

FormalRV.LatticeSurgery.LatticeSurgeryPPMContract

FormalRV/LatticeSurgery/LatticeSurgeryPPMContract.lean
FormalRV.Framework.LatticeSurgeryPPMContract — the reusable L3 lattice-surgery / PPM schedule contract. ## Motivation Previous ticks delivered isolated system-layer demos: `GE2021PPMSysInv.lean` — a 16-SysCall PPM block where I4 is vacuous (no `RequestMagicState`). `SystemLevelMagicSchedule.lean` — separate good/bad demos for I1, I2, I3, I4 individually. This file packages them as ONE reusable contract: structure PPMScheduleCert = an architecture + a SysCall stream + the derived wallclock / peak-qubit / total-qubit numbers + decidable proofs of I1 + I2 + I3 + I4 + decoder reaction. An L3 lattice-surgery PPM gadget is then represented by an inhabitant of this structure. Composition of two gadgets is a function `List PPMScheduleCert → List SysCall → Bool` that re-checks the merged invariants `decide`-ably on the merged SysCall stream. ## What this file delivers 1. `PPMScheduleCert` — the contract structure. 2. `PPMScheduleCert.all_invariants_ok` — a derived bundle theorem on any cert, restating `all_invariants_ok` from `ScheduleInvariantsExplicit`. 3. `ge2021_ppm_schedule_cert : PPMScheduleCert` — the GE2021PPMSysInv block packaged as a cert (REUSES the existing 7 invariant theorems). 4. Three PPM-pair schedules + invariant proofs: sequential / parallel-distinct / parallel-alias. 5. **I1 capacity counterexample** — an isolated capacity failure (atom outside `total_sites`). Not previously present. 6. **I3 feedback-latency counterexample** — an isolated PauliFrameUpdate-duration failure. Not previously present. 7. **Local factory-exclusivity strengthening** — a small `factory_exclusivity_ok` checker treating `RequestMagicState` as claiming a factory port, with positive + negative examples. Not a global change to `syscall_acts_on`. No Mathlib. Pure Bool / Nat / List. Decidable.
structurePPMScheduleCert
structure PPMScheduleCert
A reusable certificate for one L3 lattice-surgery / PPM gadget compiled into a SysCall stream. The architecture, syscalls, and the three constants (`t_react_us`, `window_us`, `max_per_window`) define the verification context. The remaining fields are PROOFS that the four system-level invariants hold: capacity_in_arch (I1, every claimed atom in some zone) capacity_per_cycle (I1, per-zone per-cycle aggregate) exclusivity (I2) feedback_latency (I3, PauliFrameUpdate ≤ t_cycle) decoder_react (I3, DecodeSyndrome ≤ t_react) throughput (I4, per-window magicReq count ≤ max_per_window) The wallclock proof field makes the anti-spreadsheet property explicit: `wallclock_us` is a `foldl` over the SysCall list, not a typed-in Nat.
theoremall_invariants_ok_of_cert
theorem all_invariants_ok_of_cert (c : PPMScheduleCert) :
    capacity_in_arch_ok c.arch c.syscalls
      && capacity_per_cycle_ok c.arch c.syscalls
      && exclusivity_ok c.syscalls
      && feedback_latency_ok c.arch.t_cycle_us c.syscalls = true
Derived bundle: every cert satisfies `all_invariants_ok` from `ScheduleInvariantsExplicit` (sans the not-yet-included decoder-react check, which is carried separately as `decoder_react`). The framework's `all_invariants_ok` uses `latency_speed_ok = feedback_latency_ok && speed_limit_ok`; we discharge the `feedback_latency_ok` half from `feedback_latency`, and the `speed_limit_ok` half is vacuous for the no-transit case (the cert's distance function is `fun _ => 0`, so every transit's `distance / v_max` budget is 0, trivially satisfied).
theoremthroughput_ok_of_cert
theorem throughput_ok_of_cert (c : PPMScheduleCert) :
    window_throughput_ok c.syscalls c.window_us c.max_per_window = true
Derived: cert satisfies the throughput bound at its declared window parameters.
theoremwallclock_is_derived
theorem wallclock_is_derived (c : PPMScheduleCert) :
    c.wallclock_us
      = c.syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0
Derived: cert's wallclock is the foldl over the SysCall list.
defge2021_ppm_schedule_cert
def ge2021_ppm_schedule_cert : PPMScheduleCert
The GE2021 16-SysCall PPM block as a `PPMScheduleCert`. Every proof field is a thin reference to the corresponding existing theorem in `GE2021PPMSysInv.lean`.
theoremge2021_ppm_schedule_cert_all_ok
theorem ge2021_ppm_schedule_cert_all_ok :
    capacity_in_arch_ok ge2021_ppm_schedule_cert.arch
        ge2021_ppm_schedule_cert.syscalls
      && capacity_per_cycle_ok ge2021_ppm_schedule_cert.arch
        ge2021_ppm_schedule_cert.syscalls
      && exclusivity_ok ge2021_ppm_schedule_cert.syscalls
      && feedback_latency_ok ge2021_ppm_schedule_cert.arch.t_cycle_us
        ge2021_ppm_schedule_cert.syscalls = true
*Headline**: the GE2021 PPM block, viewed as a `PPMScheduleCert`, satisfies the derived all-invariants bundle. REUSES the existing 7 invariant theorems.
theoremge2021_ppm_schedule_cert_wallclock
theorem ge2021_ppm_schedule_cert_wallclock :
    ge2021_ppm_schedule_cert.wallclock_us = 16
*Sanity**: derived wallclock for the GE2021 PPM block as a cert is 16 µs (matches existing `ppm_block_wallclock_value`).
defppm_pair_arch
def ppm_pair_arch : ZonedArch
defppm_block
def ppm_block (start_us data anc decoder_id : Nat) : List SysCall
One PPM measurement: RequestFreshAncilla + Gate2q + Measure + DecodeSyndrome. Parametric in start time, data-qubit id, and ancilla-qubit id.
defppm_pair_sequential_syscalls
def ppm_pair_sequential_syscalls : List SysCall
*Sequential pair**: PPM A in [0, 4), PPM B in [10, 14). Both use ancilla 100 — no time overlap, so I2 passes.
theoremppm_pair_sequential_capacity_in_arch_ok
theorem ppm_pair_sequential_capacity_in_arch_ok :
    capacity_in_arch_ok ppm_pair_arch ppm_pair_sequential_syscalls = true
theoremppm_pair_sequential_exclusivity_ok
theorem ppm_pair_sequential_exclusivity_ok :
    exclusivity_ok ppm_pair_sequential_syscalls = true
theoremppm_pair_sequential_feedback_latency_ok
theorem ppm_pair_sequential_feedback_latency_ok :
    feedback_latency_ok ppm_pair_arch.t_cycle_us ppm_pair_sequential_syscalls = true
theoremppm_pair_sequential_decoder_react_ok
theorem ppm_pair_sequential_decoder_react_ok :
    decoder_react_ok 10 ppm_pair_sequential_syscalls = true
theoremppm_pair_sequential_throughput_ok
theorem ppm_pair_sequential_throughput_ok :
    window_throughput_ok ppm_pair_sequential_syscalls 1000 1000 = true
theoremppm_pair_sequential_all_invariants_ok
theorem ppm_pair_sequential_all_invariants_ok :
    all_invariants_ok ppm_pair_arch ppm_pair_sequential_syscalls 1000 1000
      (fun _ => 0) = true
defppm_pair_parallel_distinct_syscalls
def ppm_pair_parallel_distinct_syscalls : List SysCall
*Parallel-distinct pair**: PPM A and PPM B run in the SAME time window [0, 4), but use DISTINCT ancillas (100 and 101). I2 passes because the only shared timing class is the different Gate2q calls with disjoint atom claims.
theoremppm_pair_parallel_distinct_exclusivity_ok
theorem ppm_pair_parallel_distinct_exclusivity_ok :
    exclusivity_ok ppm_pair_parallel_distinct_syscalls = true
theoremppm_pair_parallel_distinct_all_invariants_ok
theorem ppm_pair_parallel_distinct_all_invariants_ok :
    all_invariants_ok ppm_pair_arch ppm_pair_parallel_distinct_syscalls 1000 1000
      (fun _ => 0) = true
defppm_pair_parallel_alias_syscalls
def ppm_pair_parallel_alias_syscalls : List SysCall
*Parallel-aliasing pair (BAD)**: PPM A and PPM B both use ancilla 100 in the SAME time window. Their Gate2qs both claim atom 100 at [1, 2). I2 REJECTS.
theoremppm_pair_parallel_alias_exclusivity_fails
theorem ppm_pair_parallel_alias_exclusivity_fails :
    exclusivity_ok ppm_pair_parallel_alias_syscalls = false
theoremppm_pair_parallel_alias_fails_only_exclusivity
theorem ppm_pair_parallel_alias_fails_only_exclusivity :
    capacity_in_arch_ok ppm_pair_arch ppm_pair_parallel_alias_syscalls = true
  ∧ feedback_latency_ok ppm_pair_arch.t_cycle_us
      ppm_pair_parallel_alias_syscalls = true
  ∧ decoder_react_ok 10 ppm_pair_parallel_alias_syscalls = true
  ∧ window_throughput_ok ppm_pair_parallel_alias_syscalls 1000 1000 = true
  ∧ exclusivity_ok ppm_pair_parallel_alias_syscalls = false
Failure isolation: the aliasing pair fails ONLY I2. I1, I3, I4 still pass. This is exactly what the paper claims I2 catches when L3 gadgets are scheduled in parallel.
defcapacity_bad_schedule
def capacity_bad_schedule : List SysCall
theoremcapacity_bad_oversubscription_fails
theorem capacity_bad_oversubscription_fails :
    capacity_in_arch_ok ppm_pair_arch capacity_bad_schedule = false
theoremcapacity_bad_fails_only_capacity
theorem capacity_bad_fails_only_capacity :
    capacity_in_arch_ok ppm_pair_arch capacity_bad_schedule = false
  ∧ exclusivity_ok capacity_bad_schedule = true
  ∧ feedback_latency_ok ppm_pair_arch.t_cycle_us capacity_bad_schedule = true
  ∧ decoder_react_ok 10 capacity_bad_schedule = true
  ∧ window_throughput_ok capacity_bad_schedule 1000 1000 = true
deffeedback_bad_slow_schedule
def feedback_bad_slow_schedule : List SysCall
theoremfeedback_bad_latency_fails
theorem feedback_bad_latency_fails :
    feedback_latency_ok ppm_pair_arch.t_cycle_us feedback_bad_slow_schedule = false
theoremfeedback_bad_fails_only_feedback_latency
theorem feedback_bad_fails_only_feedback_latency :
    capacity_in_arch_ok ppm_pair_arch feedback_bad_slow_schedule = true
  ∧ exclusivity_ok feedback_bad_slow_schedule = true
  ∧ decoder_react_ok 10 feedback_bad_slow_schedule = true
  ∧ window_throughput_ok feedback_bad_slow_schedule 1000 1000 = true
  ∧ feedback_latency_ok ppm_pair_arch.t_cycle_us feedback_bad_slow_schedule = false
defsyscall_factory_claims
def syscall_factory_claims : SysCall → List Nat
  | sc => match sc.kind with
          | .RequestMagicState zone_id => [200 + zone_id]
          | _                          => []
Local: what factory port (if any) a SysCall claims. Currently only `RequestMagicState zone_id` claims port `200 + zone_id`.
deffactory_exclusivity_ok
def factory_exclusivity_ok (sched : List SysCall) : Bool
Local: factory-port exclusivity. Pairwise check that any two SysCalls overlapping in time have DISJOINT factory-port claims. Mirrors the framework's `exclusivity_ok` shape but on `syscall_factory_claims` instead of `syscall_acts_on`.
defmagic_factory_distinct_schedule
def magic_factory_distinct_schedule : List SysCall
POSITIVE: two `RequestMagicState` calls overlapping in time but targeting DIFFERENT factory zones (3 and 4). Their factory ports are distinct (203 vs 204). ACCEPTED.
theoremmagic_factory_distinct_ports_ok
theorem magic_factory_distinct_ports_ok :
    factory_exclusivity_ok magic_factory_distinct_schedule = true
defmagic_factory_same_port_schedule
def magic_factory_same_port_schedule : List SysCall
NEGATIVE: two `RequestMagicState` calls overlapping in time AND targeting the SAME factory zone (3). Both claim port 203 at the same instant. REJECTED.
theoremmagic_factory_same_port_fails
theorem magic_factory_same_port_fails :
    factory_exclusivity_ok magic_factory_same_port_schedule = false
theoremmagic_factory_same_port_passes_standard_exclusivity
theorem magic_factory_same_port_passes_standard_exclusivity :
    exclusivity_ok magic_factory_same_port_schedule = true
The same-port schedule's standard `exclusivity_ok` still PASSES — confirming the gap that the strengthening closes. `syscall_acts_on` returns `[]` for `RequestMagicState`, so the standard check is vacuous.
defppm_pair_sequential_wallclock_us
def ppm_pair_sequential_wallclock_us : Nat
Sequential pair's wallclock = 14 µs (= max end_us of PPM B's DecodeSyndrome at 14).
theoremppm_pair_sequential_wallclock_value
theorem ppm_pair_sequential_wallclock_value :
    ppm_pair_sequential_wallclock_us = 14
defppm_pair_parallel_distinct_wallclock_us
def ppm_pair_parallel_distinct_wallclock_us : Nat
Parallel-distinct pair's wallclock = 4 µs (both PPMs end at 4).
theoremppm_pair_parallel_distinct_wallclock_value
theorem ppm_pair_parallel_distinct_wallclock_value :
    ppm_pair_parallel_distinct_wallclock_us = 4
theoremppm_pair_sequential_wallclock_is_derived
theorem ppm_pair_sequential_wallclock_is_derived :
    ppm_pair_sequential_wallclock_us =
      ppm_pair_sequential_syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0
*Anti-spreadsheet (rfl)**: sequential wallclock IS the foldl.
theoremppm_pair_parallel_distinct_wallclock_is_derived
theorem ppm_pair_parallel_distinct_wallclock_is_derived :
    ppm_pair_parallel_distinct_wallclock_us =
      ppm_pair_parallel_distinct_syscalls.foldl
        (fun acc sc => Nat.max acc sc.end_us) 0
*Anti-spreadsheet (rfl)**: parallel-distinct wallclock IS the foldl.
defexclusivity_with_factory_ports_ok
def exclusivity_with_factory_ports_ok (sched : List SysCall) : Bool
Strengthened exclusivity check: standard `exclusivity_ok` AND factory-port exclusivity.
theoremexclusivity_with_factory_ports_detects_same_port
theorem exclusivity_with_factory_ports_detects_same_port :
    exclusivity_with_factory_ports_ok magic_factory_same_port_schedule = false
The same-port bad schedule fails the strengthened exclusivity check.
theoremexclusivity_with_factory_ports_accepts_distinct_ports
theorem exclusivity_with_factory_ports_accepts_distinct_ports :
    exclusivity_with_factory_ports_ok magic_factory_distinct_schedule = true
The distinct-ports good schedule passes the strengthened exclusivity check.
theoremstandard_exclusivity_misses_same_factory_port
theorem standard_exclusivity_misses_same_factory_port :
    exclusivity_ok magic_factory_same_port_schedule = true
*Diagnostic (renamed clarifying alias)**: the standard `exclusivity_ok` is silent on the same-port conflict (which is exactly why we need the strengthened bundle). Re-export of `magic_factory_same_port_passes_standard_exclusivity` from §6.
defall_invariants_with_factory_ports_ok
def all_invariants_with_factory_ports_ok
    (arch : ZonedArch) (sched : List SysCall)
    (t_react_us window_us max_per_window : Nat) : Bool
The OFFICIAL strengthened system-layer invariant bundle: capacity (I1) + exclusivity (I2) + factory-port exclusivity (I2*) + feedback latency (I3) + decoder reaction (I3) + throughput (I4). Comparison with the framework's `ScheduleInv.all_invariants_ok`: That one BUNDLES `feedback_latency_ok` + `speed_limit_ok` as `latency_speed_ok` and OMITS `decoder_react_ok`. This one EXPLICITLY includes `decoder_react_ok` and the new `factory_exclusivity_ok`. `speed_limit_ok` is omitted because the relevant schedules have no `TransitQubit` calls.
defpaper_I1_ok
def paper_I1_ok (arch : ZonedArch) (sched : List SysCall) : Bool
*Paper I1**: capacity = `capacity_in_arch_ok` ∧ `capacity_per_cycle_ok`.
defpaper_I2_strengthened_ok
def paper_I2_strengthened_ok (sched : List SysCall) : Bool
*Paper I2 (strengthened)**: exclusivity = `exclusivity_ok` ∧ `factory_exclusivity_ok`. Standard `exclusivity_ok` alone misses factory-port conflicts.
defpaper_I3_ok
def paper_I3_ok (arch : ZonedArch) (sched : List SysCall) (t_react_us : Nat) : Bool
*Paper I3**: latency = `feedback_latency_ok` ∧ `decoder_react_ok`.
defpaper_I4_ok
def paper_I4_ok (sched : List SysCall) (window_us max_per_window : Nat) : Bool
*Paper I4**: throughput = `window_throughput_ok`.
theoremall_invariants_with_factory_ports_eq_paper_invariants
theorem all_invariants_with_factory_ports_eq_paper_invariants
    (arch : ZonedArch) (sched : List SysCall)
    (t_react_us window_us max_per_window : Nat) :
    all_invariants_with_factory_ports_ok arch sched
        t_react_us window_us max_per_window
      = (paper_I1_ok arch sched
         && paper_I2_strengthened_ok sched
         && paper_I3_ok arch sched t_react_us
         && paper_I4_ok sched window_us max_per_window)
Bundle equivalence: `all_invariants_with_factory_ports_ok` is EXACTLY the conjunction `paper_I1 ∧ paper_I2_strengthened ∧ paper_I3 ∧ paper_I4`. By `rfl` since both sides unfold to the same chain of `&&`.
structurePPMScheduleCertWithFactoryPorts
structure PPMScheduleCertWithFactoryPorts
Strengthened sibling cert: same shape as `PPMScheduleCert` but with an EXTRA proof field for `factory_exclusivity_ok`.
theoremall_invariants_ok_of_cert
theorem all_invariants_ok_of_cert (c : PPMScheduleCertWithFactoryPorts) :
    all_invariants_with_factory_ports_ok
        c.arch c.syscalls c.t_react_us c.window_us c.max_per_window = true
Bundle theorem: every strengthened cert satisfies the strengthened all-invariants bundle.
theoremwallclock_is_derived
theorem wallclock_is_derived (c : PPMScheduleCertWithFactoryPorts) :
    c.wallclock_us
      = c.syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0
Derived: cert's wallclock IS the foldl over its SysCall list.
theoremge2021_ppm_block_factory_exclusivity_ok
theorem ge2021_ppm_block_factory_exclusivity_ok :
    factory_exclusivity_ok ppm_block_syscalls = true
defge2021_ppm_schedule_cert_with_factory_ports
def ge2021_ppm_schedule_cert_with_factory_ports : PPMScheduleCertWithFactoryPorts
theoremge2021_ppm_schedule_cert_with_factory_ports_all_ok
theorem ge2021_ppm_schedule_cert_with_factory_ports_all_ok :
    all_invariants_with_factory_ports_ok
        ge2021_ppm_schedule_cert_with_factory_ports.arch
        ge2021_ppm_schedule_cert_with_factory_ports.syscalls
        ge2021_ppm_schedule_cert_with_factory_ports.t_react_us
        ge2021_ppm_schedule_cert_with_factory_ports.window_us
        ge2021_ppm_schedule_cert_with_factory_ports.max_per_window = true
The GE2021 PPM block, packaged as the strengthened cert, passes the strengthened all-invariants bundle.
theoremppm_pair_sequential_factory_exclusivity_ok
theorem ppm_pair_sequential_factory_exclusivity_ok :
    factory_exclusivity_ok ppm_pair_sequential_syscalls = true
theoremppm_pair_sequential_all_invariants_with_factory_ports_ok
theorem ppm_pair_sequential_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch ppm_pair_sequential_syscalls 10 1000 1000 = true
theoremppm_pair_parallel_distinct_factory_exclusivity_ok
theorem ppm_pair_parallel_distinct_factory_exclusivity_ok :
    factory_exclusivity_ok ppm_pair_parallel_distinct_syscalls = true
theoremppm_pair_parallel_distinct_all_invariants_with_factory_ports_ok
theorem ppm_pair_parallel_distinct_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch ppm_pair_parallel_distinct_syscalls 10 1000 1000 = true
defmagic_factory_arch
def magic_factory_arch : ZonedArch
Architecture extending `magic_demo_arch` with the same structure as in `SystemLevelMagicSchedule`, used here to evaluate the strengthened bundle on the same-port bad schedule.
theoremmagic_factory_same_port_fails_strengthened_bundle
theorem magic_factory_same_port_fails_strengthened_bundle :
    all_invariants_with_factory_ports_ok
        magic_factory_arch magic_factory_same_port_schedule
        10 15 2 = false
*Strengthened-bundle headline**: the same-port bad schedule is REJECTED by the strengthened all-invariants bundle. We use `max_per_window = 2` (not 1) here so that the schedule DOES satisfy throughput — the rejection is then SPECIFICALLY from `factory_exclusivity_ok`. With `max_per_window = 1` the same schedule would also fail throughput, masking the factory-exclusivity isolation result below.
theoremmagic_factory_same_port_fails_only_factory_exclusivity
theorem magic_factory_same_port_fails_only_factory_exclusivity :
    capacity_in_arch_ok magic_factory_arch magic_factory_same_port_schedule = true
  ∧ capacity_per_cycle_ok magic_factory_arch magic_factory_same_port_schedule = true
  ∧ exclusivity_ok magic_factory_same_port_schedule = true
  ∧ factory_exclusivity_ok magic_factory_same_port_schedule = false
  ∧ feedback_latency_ok magic_factory_arch.t_cycle_us
      magic_factory_same_port_schedule = true
  ∧ decoder_react_ok 10 magic_factory_same_port_schedule = true
  ∧ window_throughput_ok magic_factory_same_port_schedule 15 2 = true
*Failure isolation**: the same-port conflict fails ONLY the factory-exclusivity check. All other six constituent checks (capacity_in_arch + capacity_per_cycle + exclusivity + feedback_latency + decoder_react + throughput) PASS at `(window_us = 15, max_per_window = 2)`. This is the paper-facing result: the strengthened bundle catches a conflict that the standard six checks all miss.
theoremmagic_factory_same_port_passes_standard_bundle
theorem magic_factory_same_port_passes_standard_bundle :
    all_invariants_ok magic_factory_arch magic_factory_same_port_schedule
        15 2 (fun _ => 0) = true
Headline-comparison theorem: standard `all_invariants_ok` also misses the same-port conflict at `(window_us = 15, max_per_window = 2)`.
theoremmagic_factory_same_port_standard_vs_strengthened
theorem magic_factory_same_port_standard_vs_strengthened :
    all_invariants_ok magic_factory_arch magic_factory_same_port_schedule
        15 2 (fun _ => 0) = true
  ∧ all_invariants_with_factory_ports_ok
        magic_factory_arch magic_factory_same_port_schedule
        10 15 2 = false
The standard bundle passes; the strengthened bundle fails.
defper_cycle_three_active_schedule
def per_cycle_three_active_schedule : List SysCall
A would-be per-cycle oversubscription witness: three Gate2qs in [0, 1) each claiming a distinct atom in the Data zone. The Data zone has range [0, 100) — capacity 100. Three distinct atoms is well within capacity. Demonstrates that distinct-atom claims cannot oversubscribe a zone whose capacity equals its range size.
theoremper_cycle_three_active_capacity_passes
theorem per_cycle_three_active_capacity_passes :
    capacity_per_cycle_ok ppm_pair_arch per_cycle_three_active_schedule = true
Confirms the structural argument: per-cycle capacity always passes when distinct atoms are used inside an atom-range-equals-capacity zone.
theoremper_cycle_three_active_exclusivity_passes
theorem per_cycle_three_active_exclusivity_passes :
    exclusivity_ok per_cycle_three_active_schedule = true
And exclusivity ALSO passes (distinct atoms, but overlapping times) — confirming that an isolated `capacity_per_cycle` failure is unreachable in the current model.
defscheduleWallclockUs
def scheduleWallclockUs (xs : List SysCall) : Nat
Wallclock of a schedule = max `end_us` across all SysCalls.
defshiftSysCall
def shiftSysCall (dt : Nat) (sc : SysCall) : SysCall
Shift a single SysCall forward in time by `dt` µs.
defshiftSchedule
def shiftSchedule (dt : Nat) (xs : List SysCall) : List SysCall
Shift every SysCall in a schedule forward by `dt` µs.
defseqSchedules
def seqSchedules (xs ys : List SysCall) : List SysCall
Sequential composition: `xs ` followed by `ys` shifted by `wallclock(xs)`. After the merge, `ys`'s SysCalls all begin at or after `xs`'s wallclock.
defparSchedules
def parSchedules (xs ys : List SysCall) : List SysCall
Parallel composition: `xs` and `ys` both starting at their original times. No time shift is applied; the merged schedule's validity must be RECHECKED (e.g., for ancilla aliasing or factory-port conflicts).
theoremscheduleWallclockUs_def
theorem scheduleWallclockUs_def (xs : List SysCall) :
    scheduleWallclockUs xs
      = xs.foldl (fun acc sc => Nat.max acc sc.end_us) 0
theoremshiftSchedule_length
theorem shiftSchedule_length (dt : Nat) (xs : List SysCall) :
    (shiftSchedule dt xs).length = xs.length
theoremseqSchedules_length
theorem seqSchedules_length (xs ys : List SysCall) :
    (seqSchedules xs ys).length = xs.length + ys.length
theoremparSchedules_length
theorem parSchedules_length (xs ys : List SysCall) :
    (parSchedules xs ys).length = xs.length + ys.length
theoremseqSchedules_wallclock_is_derived
theorem seqSchedules_wallclock_is_derived (xs ys : List SysCall) :
    scheduleWallclockUs (seqSchedules xs ys)
      = (seqSchedules xs ys).foldl (fun acc sc => Nat.max acc sc.end_us) 0
*Anti-spreadsheet (`rfl`)**: the wallclock of `seqSchedules` IS the foldl over the merged list — not a closed-form sum.
theoremparSchedules_wallclock_is_derived
theorem parSchedules_wallclock_is_derived (xs ys : List SysCall) :
    scheduleWallclockUs (parSchedules xs ys)
      = (parSchedules xs ys).foldl (fun acc sc => Nat.max acc sc.end_us) 0
*Anti-spreadsheet (`rfl`)**: same for `parSchedules`.
defseqManySchedules
def seqManySchedules : List (List SysCall) → List SysCall
  | []         => []
  | xs :: rest => seqSchedules xs (seqManySchedules rest)
Sequential composition of many schedules, recursively shifted.
defparManySchedules
def parManySchedules : List (List SysCall) → List SysCall
  | []         => []
  | xs :: rest => parSchedules xs (parManySchedules rest)
Parallel composition of many schedules, all starting at t=0.
theoremseqManySchedules_nil
theorem seqManySchedules_nil :
    seqManySchedules [] = []
theoremparManySchedules_nil
theorem parManySchedules_nil :
    parManySchedules [] = []
theoremseqManySchedules_singleton
theorem seqManySchedules_singleton (xs : List SysCall) :
    seqManySchedules [xs] = xs
Singleton case for `seqManySchedules`: equals the input (shifted by 0, since the empty tail has wallclock 0).
theoremparManySchedules_singleton
theorem parManySchedules_singleton (xs : List SysCall) :
    parManySchedules [xs] = xs
Singleton case for `parManySchedules`: equals the input.
structurePPMComposeContext
structure PPMComposeContext
Verification context for composition. Fixes the architecture and the three timing/throughput parameters under which the merged schedule will be validated.
defvalidateScheduleWithFactoryPorts
def validateScheduleWithFactoryPorts
    (arch : ZonedArch) (syscalls : List SysCall)
    (t_react_us window_us max_per_window : Nat) : Bool
The generic strengthened-bundle validator.
defPPMComposeContext.validate
def PPMComposeContext.validate
    (ctx : PPMComposeContext) (syscalls : List SysCall) : Bool
Validate a merged schedule under a `PPMComposeContext`.
defmkPPMScheduleCertWithFactoryPorts
def mkPPMScheduleCertWithFactoryPorts
    (arch : ZonedArch) (syscalls : List SysCall)
    (t_react_us window_us max_per_window : Nat)
    (h_cap : capacity_in_arch_ok arch syscalls = true)
    (h_per_cycle : capacity_per_cycle_ok arch syscalls = true)
    (h_excl : exclusivity_ok syscalls = true)
    (h_fact : factory_exclusivity_ok syscalls = true)
    (h_fbk : feedback_latency_ok arch.t_cycle_us syscalls = true)
    (h_decode : decoder_react_ok t_react_us syscalls = true)
    (h_throt : window_throughput_ok syscalls window_us max_per_window = true) :
    PPMScheduleCertWithFactoryPorts
A non-dependent direct-construction builder taking the 7 invariant proofs separately. Used internally by the bundle-based existence theorem below.
theoremmkPPMScheduleCertWithFactoryPorts_of_valid
theorem mkPPMScheduleCertWithFactoryPorts_of_valid
    (arch : ZonedArch) (syscalls : List SysCall)
    (t_react_us window_us max_per_window : Nat)
    (h : all_invariants_with_factory_ports_ok arch syscalls
           t_react_us window_us max_per_window = true) :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = arch
      ∧ cert.syscalls = syscalls
      ∧ cert.t_react_us = t_react_us
      ∧ cert.window_us = window_us
      ∧ cert.max_per_window = max_per_window
      ∧ cert.wallclock_us = scheduleWallclockUs syscalls
*Existence theorem (cert from a valid bundle)**: whenever `all_invariants_with_factory_ports_ok` holds on a schedule, a strengthened cert exists with matching fields and a derived wallclock. Unpacks the bundle into its 7 component facts and feeds them to the builder.
theoremseq_ppm_pair_cert_exists
theorem seq_ppm_pair_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ppm_pair_arch
      ∧ cert.syscalls = ppm_pair_sequential_syscalls
      ∧ cert.wallclock_us = scheduleWallclockUs ppm_pair_sequential_syscalls
*Sequential PPM-pair cert exists**: the existing `ppm_pair_sequential_syscalls` produces a cert under the `ppm_pair_arch` + standard parameters.
theorempar_ppm_pair_distinct_cert_exists
theorem par_ppm_pair_distinct_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ppm_pair_arch
      ∧ cert.syscalls = ppm_pair_parallel_distinct_syscalls
      ∧ cert.wallclock_us = scheduleWallclockUs ppm_pair_parallel_distinct_syscalls
*Parallel-distinct PPM-pair cert exists**.
theoremvalidate_parallel_alias_false
theorem validate_parallel_alias_false :
    validateScheduleWithFactoryPorts
        ppm_pair_arch ppm_pair_parallel_alias_syscalls 10 1000 1000 = false
*Parallel-aliasing PPM-pair is REJECTED at the validator level**: no strengthened cert can be constructed because the merged schedule fails `exclusivity_ok`.
defppm_compose_A
def ppm_compose_A : List SysCall
Block A: a PPM block at `start_us = 0` on data 0, ancilla 100.
defppm_compose_B_same_anc
def ppm_compose_B_same_anc : List SysCall
Block B: a PPM block at `start_us = 0` on data 50, ancilla 100. Same ancilla as A — for sequential composition this is fine (B gets shifted past A's wallclock); for parallel composition it causes aliasing.
defppm_compose_B_distinct_anc
def ppm_compose_B_distinct_anc : List SysCall
Block B with a DISTINCT ancilla (101).
defppm_compose_C_distinct_anc
def ppm_compose_C_distinct_anc : List SysCall
Block C with a third distinct ancilla (102).
defseq_compose_AB
def seq_compose_AB : List SysCall
*Sequential composition of A then B (same ancilla, but shifted so B starts at wallclock(A) = 4)**: PASSES the strengthened bundle.
theoremseq_compose_AB_all_invariants_with_factory_ports_ok
theorem seq_compose_AB_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch seq_compose_AB 10 1000 1000 = true
theoremseq_compose_AB_wallclock_is_derived
theorem seq_compose_AB_wallclock_is_derived :
    scheduleWallclockUs seq_compose_AB
      = seq_compose_AB.foldl (fun acc sc => Nat.max acc sc.end_us) 0
The seq composition's wallclock derives from `foldl`, not a typed-in number.
defpar_compose_AB_distinct
def par_compose_AB_distinct : List SysCall
*Parallel composition of A and B (distinct ancillas)**: PASSES.
theorempar_compose_AB_distinct_all_invariants_with_factory_ports_ok
theorem par_compose_AB_distinct_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch par_compose_AB_distinct 10 1000 1000 = true
defpar_compose_AB_alias
def par_compose_AB_alias : List SysCall
*Parallel composition of A and B (same ancilla)**: REJECTED by exclusivity, since both Gate2qs at [1, 2) claim site 100. (Legacy `atom` is read as `site` in platform-neutral terms; see `SurgeryGadgetToSysCalls.lean` §0.)
theorempar_compose_AB_alias_rejected
theorem par_compose_AB_alias_rejected :
    validateScheduleWithFactoryPorts
        ppm_pair_arch par_compose_AB_alias 10 1000 1000 = false
defppm_triple_sequential_syscalls
def ppm_triple_sequential_syscalls : List SysCall
*3-PPM sequential**: A then B then C, each shifted past the previous's wallclock. All distinct data qubits and ancillas (the alias-safety hypothesis for sequential isn't required here since the times are disjoint anyway).
theoremppm_triple_sequential_all_invariants_with_factory_ports_ok
theorem ppm_triple_sequential_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch ppm_triple_sequential_syscalls 10 1000 1000 = true
theoremppm_triple_sequential_wallclock_is_derived
theorem ppm_triple_sequential_wallclock_is_derived :
    scheduleWallclockUs ppm_triple_sequential_syscalls
      = ppm_triple_sequential_syscalls.foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
defppm_triple_parallel_distinct_syscalls
def ppm_triple_parallel_distinct_syscalls : List SysCall
*3-PPM parallel-distinct**: A, B, C all at t=0..4 using distinct ancillas 100, 101, 102.
theoremppm_triple_parallel_distinct_all_invariants_with_factory_ports_ok
theorem ppm_triple_parallel_distinct_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok
        ppm_pair_arch ppm_triple_parallel_distinct_syscalls 10 1000 1000 = true
theoremppm_triple_parallel_distinct_wallclock_is_derived
theorem ppm_triple_parallel_distinct_wallclock_is_derived :
    scheduleWallclockUs ppm_triple_parallel_distinct_syscalls
      = ppm_triple_parallel_distinct_syscalls.foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
theoremcomposeSeqSchedulesWithFactoryPorts_of_valid
theorem composeSeqSchedulesWithFactoryPorts_of_valid
    (ctx : PPMComposeContext) (blocks : List (List SysCall))
    (h : all_invariants_with_factory_ports_ok ctx.arch
           (seqManySchedules blocks)
           ctx.t_react_us ctx.window_us ctx.max_per_window = true) :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ctx.arch
      ∧ cert.syscalls = seqManySchedules blocks
      ∧ cert.wallclock_us = scheduleWallclockUs (seqManySchedules blocks)
*Compose-many existence theorem**: given a list of SysCall sub-streams (one per PPM gadget), if the SEQUENTIALLY merged stream passes the strengthened bundle under the given context, then a strengthened cert exists for the merged stream.
theoremcomposeParSchedulesWithFactoryPorts_of_valid
theorem composeParSchedulesWithFactoryPorts_of_valid
    (ctx : PPMComposeContext) (blocks : List (List SysCall))
    (h : all_invariants_with_factory_ports_ok ctx.arch
           (parManySchedules blocks)
           ctx.t_react_us ctx.window_us ctx.max_per_window = true) :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ctx.arch
      ∧ cert.syscalls = parManySchedules blocks
      ∧ cert.wallclock_us = scheduleWallclockUs (parManySchedules blocks)
*Compose-many existence theorem (parallel variant)**.
defppm_triple_ctx
def ppm_triple_ctx : PPMComposeContext
Worked applications of the compose-many theorems on the 3-PPM schedules from §20.
theoremppm_triple_sequential_cert_exists
theorem ppm_triple_sequential_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ppm_triple_ctx.arch
      ∧ cert.syscalls = ppm_triple_sequential_syscalls
theoremppm_triple_parallel_distinct_cert_exists
theorem ppm_triple_parallel_distinct_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ppm_triple_ctx.arch
      ∧ cert.syscalls = ppm_triple_parallel_distinct_syscalls

FormalRV.LatticeSurgery.MagicInjectionSurgery

FormalRV/LatticeSurgery/MagicInjectionSurgery.lean
FormalRV.LatticeSurgery.MagicInjectionSurgery — `teleportCCX` → magic-injection LATTICE SURGERY, the reduction that turns the last abstract command of the Shor PPM program into a concrete surface-code surgery schedule. ## The reduction A logical CCZ / Toffoli is NON-CLIFFORD, so lattice surgery alone cannot do it: it consumes a |CCZ⟩ MAGIC STATE. Gate teleportation (Litinski 2019): prepare |CCZ⟩ on three ancilla patches, then couple each data patch (a,b,c) to its magic patch by a lattice-surgery MERGE (a logical Pauli-product measurement); outcome-conditioned Clifford (CZ/Z) corrections finish the teleportation, and the data has had CCZ applied. So: teleportCCX a b c = [provision 1 |CCZ⟩ magic state] (resource) ++ cczInjectionSchedule (3 surgery merges) (THIS file) ++ [outcome-conditioned Clifford corrections]. (Clifford) We make the MIDDLE term concrete: a `SurgerySchedule.Schedule` of three merge gadgets, which REDUCES to its surgery merges (`schedule_runs_as_surgeries`), and whose resource is counted (3 merges + exactly 1 magic state). ## Honesty boundary (precise) The NON-CLIFFORD bit-level action (`t.bits = applyNat (CCX a b c) s.bits`) is carried by the consumed magic state and is the EXISTING contract `CircuitToPPMToffoliMagic.teleportCCXRel` (the established gate-teleportation identity — `teleportCCXProgram_correct_on_success`). THIS file discharges the remaining structural gap: that `teleportCCX`'s lattice-surgery realisation is a concrete, reducing, resource-counted surgery schedule — not an abstract command. The Heisenberg↔Schrödinger (Gottesman–Knill) faithfulness bridging the stabilizer surgery layer to the magic-basis bit layer remains the delimited residue (as in `SurfaceShorPPMEndToEnd`). No `sorry`, no new `axiom`.
defcczInjectionSchedule
def cczInjectionSchedule (mA mB mC : SurgeryGadget) : Schedule
The CCZ magic-state INJECTION as a surface-code surgery SCHEDULE: three logical Pauli-product-measurement merges, one coupling each data patch to its |CCZ⟩-magic-state patch. (After these merges + outcome-conditioned Clifford corrections, CCZ is teleported onto the data.)
theoremcczInjection_reduces
theorem cczInjection_reduces (mA mB mC : SurgeryGadget) (s : StabilizerState) :
    zxRun (scheduleProgramX (cczInjectionSchedule mA mB mC)) s
      = runScheduleX (cczInjectionSchedule mA mB mC) s
*The injection reduces to its three surgery merges** — `teleportCCX`'s lattice-surgery realisation runs exactly as the sequence of surface-code merges (operational, via the whole-schedule reduction). Gadget-general.
theoremteleportCCX_one_magic
theorem teleportCCX_one_magic (a b c : Nat) :
    magicPPMRequestCount [MagicPPMCommand.teleportCCX a b c] = 1
*Magic accounting.** One `teleportCCX` consumes exactly ONE magic state (the |CCZ⟩), to be produced by the T-factory — the resource that pays for the non-Clifford gate.
theoremcczInjection_rounds
theorem cczInjection_rounds (mA mB mC : SurgeryGadget) :
    scheduleTotalRounds (cczInjectionSchedule mA mB mC)
      = mA.tau_s + mB.tau_s + mC.tau_s
*Surgery TIME of one CCZ injection**: the three merges' verified `tau_s` add.
theoremcczInjection_verified
theorem cczInjection_verified (mA mB mC : SurgeryGadget)
    (hA : SurgeryGadget.verify_surgery_gadget mA = true)
    (hB : SurgeryGadget.verify_surgery_gadget mB = true)
    (hC : SurgeryGadget.verify_surgery_gadget mC = true) :
    (cczInjectionSchedule mA mB mC).all
        (fun g => SurgeryGadget.verify_surgery_gadget g) = true
*All gadgets in an injection are structurally verified** when each is.
theoremteleportCCX_surface_realisation
theorem teleportCCX_surface_realisation (a b c : Nat) (s : StabilizerState) :
    -- (i) operational reduction of the lattice-surgery realisation:
    (zxRun (scheduleProgramX
        (cczInjectionSchedule surface3_x_surgery surface3_x_surgery surface3_x_surgery)) s
      = runScheduleX
        (cczInjectionSchedule surface3_x_surgery surface3_x_surgery surface3_x_surgery) s)
    -- (ii) all three merges structurally verified:
    ∧ (cczInjectionSchedule surface3_x_surgery surface3_x_surgery surface3_x_surgery).all
        (fun g => SurgeryGadget.verify_surgery_gadget g) = true
    -- (iii) one magic state consumed:
    ∧ magicPPMRequestCount [MagicPPMCommand.teleportCCX a b c] = 1
    -- (iv) surgery time = 6 syndrome rounds:
A `teleportCCX` realised on three verified surface-code merges: (i) the surgery schedule REDUCES to its merges, (ii) every merge is verified, (iii) it consumes 1 magic state, (iv) costs 3·2 = 6 syndrome rounds.

FormalRV.LatticeSurgery.ScheduleEmit

FormalRV/LatticeSurgery/ScheduleEmit.lean
FormalRV.LatticeSurgery.ScheduleEmit — emit a whole SURGERY SCHEDULE as one composed Stim circuit (the detailed, system-level scheduled physical circuit a third party can run), generalising `StimEmit.surgeryToStim` from a single gadget to a sequence laid out on DISJOINT physical-qubit ranges. This is the codegen half of the "emit detailed code for any N/a" goal: a verified schedule (`SurgerySchedule.Schedule`) → a Stim program whose every stabiliser is an explicit gate sequence. Correctness is justified EXTERNALLY by Stim's stabiliser-flow analysis (PyCircuits/), the same gold standard the rest of the project uses. No Mathlib. Pure String emission (no theorems about semantics here — those live in `SurgeryDemoSurface` / `SurgeryCorrect`; this file is the emitter).
defgadgetFootprint
def gadgetFootprint (g : SurgeryGadget) : Nat
Physical-qubit footprint of one gadget's emitted circuit: data + surgery ancilla (`merged_n`) plus one syndrome ancilla per merged check.
defsurgeryToStimAt
def surgeryToStimAt (g : SurgeryGadget) (off : Nat) : String
Emit one gadget's merged-code syndrome circuit with ALL qubit indices shifted by `off`, so distinct schedule entries occupy disjoint physical-qubit ranges.
defemitScheduleStimFrom
def emitScheduleStimFrom : Schedule → Nat → String
  | [],        _   => ""
  | g :: rest, off =>
      surgeryToStimAt g off ++ "TICK\n" ++ emitScheduleStimFrom rest (off + gadgetFootprint g)
Emit a whole schedule: each gadget at the running offset (sum of prior footprints), separated by `TICK`. Carries the offset explicitly.
defemitScheduleStim
def emitScheduleStim (sched : Schedule) : String
The detailed scheduled physical circuit for a surgery schedule (offset 0).
defscheduleFootprint
def scheduleFootprint (sched : Schedule) : Nat
Total physical qubits the emitted scheduled circuit uses = the sum of the per-gadget footprints (disjoint placement).
theoremfoldl_add_replicate
private theorem foldl_add_replicate (n acc c : Nat) :
    (List.replicate n c).foldl (· + ·) acc = acc + n * c
theoremscheduleFootprint_replicate
theorem scheduleFootprint_replicate (n : Nat) (g : SurgeryGadget) :
    scheduleFootprint (List.replicate n g) = n * gadgetFootprint g
Footprint of a schedule of `n` identical gadgets is `n · footprint` — the space the emitted code occupies grows linearly in the schedule length.

FormalRV.LatticeSurgery.StimEmit

FormalRV/LatticeSurgery/StimEmit.lean
FormalRV.LatticeSurgery.StimEmit — emit a verified surgery gadget's merged-code stabilizer-measurement circuit as a Stim program (the framework producing the actual compiled surface-code circuit), for cross-validation against Stim (the reference Gottesman–Knill simulator) and downstream TQEC tooling. Path A tooling (John 2026-06-02): debug/validate the surgery construction with Stim, and make the framework emit Stim/TQEC code. The emitted circuit is the DETAILED physical syndrome extraction of the merged code: for each merged X-check (support S) an ancilla in |+⟩, `CX anc→s` for s∈S, measure X; for each merged Z-check an ancilla in |0⟩, `CX s→anc`, measure Z. Measurement records appear in order: X-checks first (rec 0..|hx|−1), then Z-checks. A Stim FLOW check (in `PyCircuits/`) then confirms the span_witness-selected X-check records read the logical X̄ — independently reproducing `surface3_x_surgery_measures_logicalX`. No Mathlib. Pure String emission. (No theorems here — this is the codegen bridge; the SEMANTICS are proven in `SurgeryDemoSurface` / `SurgeryCorrect`.)
defrowSupport
def rowSupport (row : List Bool) : List Nat
The support (list of qubit indices where the row is `true`) of a check row.
defnl
private def nl : String
defxCheckBlock
def xCheckBlock (anc : Nat) (support : List Nat) : String
One X-check measurement block: ancilla `anc` in |+⟩, `CX anc→s` for each support qubit `s`, measure ancilla in X.
defzCheckBlock
def zCheckBlock (anc : Nat) (support : List Nat) : String
One Z-check measurement block: ancilla `anc` in |0⟩, `CX s→anc` for each support qubit `s`, measure ancilla in Z.
defsurgeryToStim
def surgeryToStim (g : SurgeryGadget) : String
Emit the merged-code stabilizer-measurement circuit of a surgery gadget as a Stim program. Data + surgery-ancilla qubits are `0..merged_n−1`; the syndrome-measurement ancillas are `merged_n + i`. X-checks are emitted first (records `0..|hx|−1`), then Z-checks.

FormalRV.LatticeSurgery.SurfaceShorFullSchedule

FormalRV/LatticeSurgery/SurfaceShorFullSchedule.lean
FormalRV.LatticeSurgery.SurfaceShorFullSchedule — the FULL detailed system-level schedule of a surface-code Shor fragment, with BOTH the resource-invariant check (A) AND the causal-dependency check (B) verified together. This is the system-layer capstone: a concrete, time-resolved `SysCall` schedule for two logical Toffolis of Shor's modular exponentiation, each compiled to a surface-code magic-injection lattice surgery (one |CCZ⟩ request + three M_ZZ merges) interleaved with syndrome extraction, decoding, and feed-forward Pauli corrections — and the two sub-circuits sequenced causally. We prove the schedule satisfies, by ONE uniform `checkAll`: • (A) RESOURCE conflict-freedom — capacity, exclusivity, latency, T-factory throughput, decoder reaction (`baseInvariants`); and • (B) CAUSAL dependencies — every producer finishes before its consumer starts (`causalityInv shorDeps`): magic→merge, merge+syndrome→decode, decode→feed-forward, and sub-circuit C₁→C₂ (qianxu App. E). Negative tests show each class independently rejects a violating schedule. Hardware-neutral: `moves := []`, so (per `SurfaceSystemCompile`) the schedule is valid on superconducting AND neutral-atom platforms. Connection to the verified circuit layer: the 2 `RequestMagicState` are the 2 Toffolis' magic states (one each, `teleportCCX_one_magic`); the 6 merge `Measure`s are the 2×3 surgery merges of `cczInjectionSchedule` (`MagicInjectionSurgery`). Qubit indices lie in disjoint layout patches (`SurfaceSystemCompile.patches_disjoint`). No `sorry`, no new `axiom`.
defshorSched
def shorSched : List SysCall
defshorDeps
def shorDeps : DepGraph
defshorCtx
def shorCtx : SystemCtx
theoremshorCtx_resource_ok
theorem shorCtx_resource_ok : checkAll baseInvariants shorCtx = true
The detailed two-Toffoli surface-code schedule passes every base invariant: capacity, exclusivity, latency, T-factory throughput (≤1 |CCZ⟩ per 26 µs window — one factory), and decoder reaction.
theoremshorCtx_causality_ok
theorem shorCtx_causality_ok : respectsCausality shorSched shorDeps = true
The schedule RESPECTS every causal edge — magic→merge, merge+syndrome→decode, decode→feed-forward, and the sequential C₁→C₂ ordering.
theoremshorCtx_fully_valid
theorem shorCtx_fully_valid :
    checkAll (baseInvariants ++ [causalityInv shorDeps]) shorCtx = true
*FULL SYSTEM-LEVEL CORRECTNESS.** The detailed surface-code Shor schedule satisfies RESOURCE conflict-freedom AND CAUSAL dependencies under one uniform `checkAll` — the "max parallelism subject to (A) and (B)" criterion, machine- checked on a fully time-resolved physical schedule.
defbadCausalSched
def badCausalSched : List SysCall
Putting T2's feed-forward (13) BEFORE its decode (12) breaks edge ⟨12,13⟩.
defbadCausalCtx
def badCausalCtx : SystemCtx
theorembadCausal_resource_ok
theorem badCausal_resource_ok : checkAll baseInvariants badCausalCtx = true
It still passes the RESOURCE invariants (A)…
theorembadCausal_causality_fails
theorem badCausal_causality_fails :
    (causalityInv shorDeps).check badCausalCtx = false
…but FAILS causality (B): a correction cannot precede the decode producing it.
theorembadCausal_unified_fails
theorem badCausal_unified_fails :
    checkAll (baseInvariants ++ [causalityInv shorDeps]) badCausalCtx = false
…so the unified check rejects it.
defbadThroughputSched
def badThroughputSched : List SysCall
Asking BOTH Toffolis' |CCZ⟩ in the SAME window (T2 magic at 5 µs) exceeds the one-factory throughput — RESOURCE (A) rejects it, independently of causality.
defbadThroughputCtx
def badThroughputCtx : SystemCtx
theorembadThroughput_resource_fails
theorem badThroughput_resource_fails :
    checkAll baseInvariants badThroughputCtx = false
theoremtwo_magic_requests
theorem two_magic_requests :
    (shorSched.filter (fun sc => match sc.kind with
      | SysCallKind.RequestMagicState _ => true | _ => false)).length = 2
The schedule issues exactly 2 magic-state requests = 2 Toffolis, one |CCZ⟩ each (`MagicInjectionSurgery.teleportCCX_one_magic`).
theoremsix_merge_measurements
theorem six_merge_measurements :
    (shorSched.filter (fun sc => match sc.kind with
      | SysCallKind.Measure q _ => decide (10 ≤ q) | _ => false)).length = 6
The schedule issues exactly 6 merge measurements = 2 Toffolis × 3 M_ZZ merges (`MagicInjectionSurgery.cczInjectionSchedule` is a 3-merge schedule).

FormalRV.LatticeSurgery.SurfaceShorFullStack

FormalRV/LatticeSurgery/SurfaceShorFullStack.lean
FormalRV.LatticeSurgery.SurfaceShorFullStack — the SCHEDULE-LEVEL capstone of Path A: a multi-PPM surface-code schedule of VERIFIED logical measurements, proven to reduce to its sequence of surgery merges, AND resource-counted. This upgrades `SurfaceShorPPMEndToEnd` (which realised ONE logical PPM on the surface code) to an ARBITRARY-LENGTH schedule, using the whole-schedule reduction `SurgerySchedule.schedule_runs_as_surgeries`. It then attaches the post-verification resource count (`SurfaceShorResourceCount`): the schedule's TIME is the sum of the per-merge `tau_s` (`scheduleTotalRounds`, = n·tau_s for n PPMs), and its SPACE is the (reused) per-merge physical footprint. ## The L1→L4 stack, assembled L1 (algorithm) `shor_succeeds_with_ppm_realized_modmult` — order finding succeeds, modular-multiplier oracle observed correctly. L2→L3 (PPM) each logical operation is a Pauli-product measurement; a schedule of them is `scheduleProgramX`. L3→L4 (surgery) `schedule_runs_as_surgeries` — the schedule's PPM program runs EXACTLY as the sequence of surface-code surgery merges, each `surface3_x_surgery` structurally verified and measuring X̄. resource `scheduleTotalRounds` (time) + `surgeryPhysQubits` (space), counted on the VERIFIED objects. ## Honesty boundary (unchanged from `SurfaceShorPPMEndToEnd`) `demoSchedule` is a CONCRETE length-3 schedule of verified logical-X̄ merges; it stands in for a prefix of Shor's actual PPM sequence (the reduction is gadget-general, so it applies once that sequence is enumerated — and the enumeration of every Shor PPM, with `teleportCCX` magic injection, remains the deferred contract). Merged-code distance / FT and Gottesman–Knill Hilbert-space faithfulness also remain delimited there. No `sorry`, no new `axiom`.
defdemoSchedule
def demoSchedule : Schedule
A concrete surface-code SCHEDULE: a length-3 fragment of logical-X̄ PPMs on the verified [[13,1,3]] code. Stands for a prefix of Shor's PPM sequence; the reduction below is gadget-general.
theoremdemoSchedule_verified
theorem demoSchedule_verified :
    demoSchedule.all (fun g => SurgeryGadget.verify_surgery_gadget g) = true
Every gadget in the schedule passes the structural verifier.
theoremdemoSchedule_reduces
theorem demoSchedule_reduces (s : StabilizerState) :
    zxRun (scheduleProgramX demoSchedule) s = runScheduleX demoSchedule s
*The whole schedule reduces to its surgery merges** (the multi-PPM enumeration, instantiated on the concrete schedule).
theoremfoldl_add_replicate
private theorem foldl_add_replicate (n acc c : Nat) :
    (List.replicate n c).foldl (· + ·) acc = acc + n * c
theoremschedule_rounds_replicate
theorem schedule_rounds_replicate (n : Nat) (g : SurgeryGadget) :
    scheduleTotalRounds (List.replicate n g) = n * g.tau_s
*Schedule time law.** A schedule of `n` identical logical-PPM merges runs for `n · tau_s` syndrome rounds — the per-merge verified `tau_s` scaled by the number of PPMs.
theoremdemoSchedule_total_rounds
theorem demoSchedule_total_rounds : scheduleTotalRounds demoSchedule = 6
The demo schedule's TIME: 3 PPMs × 2 rounds = 6 syndrome rounds.
theoremdemoSchedule_space
theorem demoSchedule_space : surgeryPhysQubits surface3_x_surgery = 28
The demo schedule's SPACE: the per-merge physical footprint, 28 qubits — the same patches are REUSED across the schedule (space is the max, not the sum; only time accumulates).
theoremsurface_schedule_full_stack
theorem surface_schedule_full_stack (s : StabilizerState) :
    demoSchedule.all (fun g => SurgeryGadget.verify_surgery_gadget g) = true
    ∧ zxRun (scheduleProgramX demoSchedule) s = runScheduleX demoSchedule s
    ∧ scheduleTotalRounds demoSchedule = 6
    ∧ surgeryPhysQubits surface3_x_surgery = 28
*SCHEDULE-LEVEL CAPSTONE.** A multi-PPM surface-code schedule of VERIFIED logical measurements (i) is structurally verified gadget-by-gadget, (ii) reduces operationally to its sequence of surgery merges, and (iii) is resource-counted — time `= n · tau_s = 6` rounds, space `= 28` (reused) physical qubits. Composes with `shor_succeeds_with_ppm_realized_modmult` (L1) and `surface_shor_ppm_physically_realized` (per-surgery L3→L4) for the full stack.

FormalRV.LatticeSurgery.SurfaceShorPPMEndToEnd

FormalRV/LatticeSurgery/SurfaceShorPPMEndToEnd.lean
FormalRV.LatticeSurgery.SurfaceShorPPMEndToEnd — the capstone of Path A: PPM-based Shor's algorithm, joined to a FULLY COMPILED surface-code realisation of a logical Pauli-product measurement (lattice surgery + detailed syndrome extraction), semantically verified. ## What this proves (and its honest scope) `surface_shor_ppm_physically_realized` conjoins, at the SAME parameters, two sorry-free results: (I) PPM-LEVEL SHOR (reused verbatim from `ShorPPMEndToEnd.shor_succeeds_with_ppm_realized_modmult`): order finding succeeds with probability ≥ κ/(log₂N)⁴, and the modular-multiplier oracle is compiled to a magic-aware PPM program that runs on a factory pool and observes the correct modular product. (II) SURFACE-CODE REALISATION of a logical PPM (this Path-A contribution): a representative logical Pauli-product measurement — the logical X̄ of the surface code [[13,1,3]] — is FULLY COMPILED to a physical surface-code circuit and verified: the surgery gadget passes the structural verifier (`surface3_x_surgery_verifies`); it MEASURES the logical X̄ — the readout (R) of the code-general, axiom-free `surgery_implements_logical_measurement` (`surface3_x_surgery_measures_logicalX`); the LATTICE SURGERY is the syndrome extraction of the merged code, whose detailed CSS syndrome circuit (one ancilla + CNOTs + measurement per merged check, `CliffordConj`-realised) implements the merge (`surface3_merged_syndrome_circuit_implements`). ## Honesty boundary (precise — read before citing) This is a CONJUNCTION, NOT a reduction. We prove "Shor (at the PPM level) succeeds AND each logical PPM it abstracts is realisable by a verified surface-code surgery gadget with an explicit physical CSS syndrome circuit". We do NOT prove "the Shor PPM program literally executes as a single surface schedule". The deferred contract (exactly as `ShorPPMEndToEnd` already delimits `teleportCCXRel`, factory distillation, QPE, decoder) is: the operational reduction of each `MagicPPMCommand` (`teleportCCX` / `base`) to a concrete sequence of surgery gadgets, and the enumeration of ALL of Shor's PPMs into one composed surface circuit; merged-code DISTANCE / fault-tolerant error suppression; the Gottesman–Knill Hilbert-space faithfulness of the Heisenberg picture. What is NEW and verified here: the PPM-on-a-code gap John flagged is closed for the surface code — a logical PPM is no longer an abstract command but a concrete, structurally-verified, logically-correct surface-code surgery whose every stabiliser is an explicit gate circuit. No Mathlib beyond what `ShorPPMEndToEnd` already pulls (the success bound is over ℝ). No `sorry`; no NEW axioms beyond those of conjunct (I).
theoremsurface_shor_ppm_physically_realized
theorem surface_shor_ppm_physically_realized
    (F : TFactoryContract)
    (a r N m bits ainv x : Nat)
    (h_setting : ShorSetting a r N m bits)
    (h_sizing : CircuitSizing N bits)
    (h_inv : a * ainv % N = 1)
    (h_ainv_le : ainv ≤ N) (hx : x < N)
    (signs : List Bool)
    (hsig : signs.length = surface3_x_surgery.merged_hx.length) :
    -- (I) PPM-level Shor (reused):
    (FormalRV.SQIRPort.probability_of_success a r N m bits
        (ModMul.ancillaWidth bits) (ModMul.circuitFamily a ainv N bits)
*CAPSTONE (Path A): PPM-Shor succeeds, AND a logical PPM is fully realised by a verified surface-code circuit (lattice surgery + detailed syndrome extraction).** (I) is `shor_succeeds_with_ppm_realized_modmult` verbatim; (II) is the surface-code realisation of the logical X̄ PPM. See the file header for the precise honesty boundary (this is a conjunction, not a whole-program reduction).

FormalRV.LatticeSurgery.SurfaceShorResourceCount

FormalRV/LatticeSurgery/SurfaceShorResourceCount.lean
FormalRV.LatticeSurgery.SurfaceShorResourceCount — RESOURCE COUNT of the surface-code lattice-surgery realisation of Shor, derived AFTER semantic verification. This file is governed by the project's hard rule "semantic correctness BEFORE resource counts" (CLAUDE.md, 2026-05-13). The per-operation primitive counted here is `surface3_x_surgery` — the [[13,1,3]] surface code's logical X̄ measured by lattice surgery — which is PROVEN: structurally valid (`surface3_x_surgery_verifies`), to MEASURE the logical X̄ (`surface3_x_surgery_measures_logicalX`, the readout of the axiom-free, code-general `surgery_implements_logical_measurement`), realised by an explicit physical CSS syndrome circuit (`surface3_merged_syndrome_circuit_implements`, emitted gate-by-gate by `StimEmit.surgeryToStim`, Stim-flow cross-validated in PyCircuits/). ONLY THEN do we count its physical resources. ## Three parts Part A resource functions on ANY surgery gadget's emitted circuit (`StimEmit.surgeryToStim`): physical qubits, CNOTs, measurements, rounds. Parametric — reusable for any verified gadget / any code. Part B the EXACT counts of the verified surface3 X̄ surgery (`by decide`). Part C the Shor-scale figure: plug the verified surface3 code into the reusable, rfl-verified `surfaceModel` cost model with a paper-cited Toffoli count. ## Honesty boundary Part A/B are exact counts of the VERIFIED primitive. Part C is a PARAMETRIC estimate: it composes the verified primitive's per-patch area and the code distance with a Toffoli count through the verified cost-model derivation (`estimateWith_qubits/time`, proven `∀ model` by `rfl`). It is NOT a claim that the whole Shor program is enumerated into one schedule — that enumeration is the deferred contract delimited in `SurfaceShorPPMEndToEnd`. It IS a resource model whose every per-operation input is a verified quantity. No `sorry`, no new `axiom`.
defrowWeight
def rowWeight (row : List Bool) : Nat
Hamming weight of a check row = number of CNOTs that check contributes.
defsurgeryPhysQubits
def surgeryPhysQubits (g : SurgeryGadget) : Nat
Physical qubits of the emitted circuit: `merged_n` (data + surgery ancilla) plus one syndrome ancilla per merged check (X-checks then Z-checks).
defsurgeryCNOTs
def surgeryCNOTs (g : SurgeryGadget) : Nat
Two-qubit gates (CNOTs) in one syndrome round = total check weight.
defsurgeryMeasPerRound
def surgeryMeasPerRound (g : SurgeryGadget) : Nat
Measurements in one syndrome round = one per merged check.
defsurgeryRounds
def surgeryRounds (g : SurgeryGadget) : Nat
Syndrome rounds the merge runs for (the gadget's verified `tau_s`).
defsurgeryTotalMeas
def surgeryTotalMeas (g : SurgeryGadget) : Nat
Total measurements over the whole merge = per-round × rounds.
theoremcounted_surgery_is_verified
theorem counted_surgery_is_verified :
    SurgeryGadget.verify_surgery_gadget surface3_x_surgery = true
The counted primitive is the structurally-verified gadget. Its full semantic correctness (it MEASURES the logical X̄) is `surface3_x_surgery_measures_logicalX`; we re-expose the structural verifier here as the gate that the resource count is allowed to proceed.
theoremsurface3_phys_qubits
theorem surface3_phys_qubits : surgeryPhysQubits surface3_x_surgery = 28
The [[13,1,3]] logical-X̄ lattice surgery uses **28 physical qubits** (14 data+ancilla + 8 X-syndrome + 6 Z-syndrome ancillas).
theoremsurface3_cnots
theorem surface3_cnots : surgeryCNOTs surface3_x_surgery = 45
…**45 CNOTs** per syndrome round (25 in the X-checks, 20 in the Z-checks).
theoremsurface3_meas_per_round
theorem surface3_meas_per_round : surgeryMeasPerRound surface3_x_surgery = 14
…**14 measurements** per round (8 X-checks + 6 Z-checks).
theoremsurface3_rounds
theorem surface3_rounds : surgeryRounds surface3_x_surgery = 2
…over **2 syndrome rounds** (the verified `tau_s`).
theoremsurface3_total_meas
theorem surface3_total_meas : surgeryTotalMeas surface3_x_surgery = 28
…for **28 measurements** total — matching the Stim-flow cross-validation in `PyCircuits/validate_surface3_stim.py` (28 qubits, 14 measurements/round).
defshorWorkload
def shorWorkload (T L : Nat) : Workload
A Shor workload: `T` logical Toffolis on `L` logical (data) qubits.
theoremsurface3_physPerLogical
theorem surface3_physPerLogical : physPerLogical surface3_qec = 13
physPerLogical of the verified [[13,1,3]] code is its data count, 13.
theoremsurface3_distance
theorem surface3_distance : surface3_qec.d = 3
Code distance of the verified surface3 code is 3.
theoremshor_surface_qubits
theorem shor_surface_qubits (T L factory : Nat) (hw : Hardware) (ow p : Nat) :
    (estimateWith (surfaceModel factory) hw (shorWorkload T L) surface3_qec ow p).qubits
      = L * 26 + factory
*Surface-code Shor physical qubits.** Through the verified surface model: `L` logical patches of the verified [[13,1,3]] code (26 physical qubits each: data + routing) plus the magic-state factory.
theoremshor_surface_time
theorem shor_surface_time (T L factory : Nat) (hw : Hardware) (ow p : Nat) :
    (estimateWith (surfaceModel factory) hw (shorWorkload T L) surface3_qec ow p).time_us_tenths
      = T * 3 * hw.cycle_time_us_tenths
*Surface-code Shor runtime.** `T` logical Toffolis, each `d = 3` code cycles, at the hardware cycle time.
theoremctl_adder4_surface_qubits
theorem ctl_adder4_surface_qubits (L f : Nat) (hw : Hardware) :
    (estimateWith (surfaceModel f) hw
        (shorWorkload (ctl_adder_total_toffolis_n_bit 4) L) surface3_qec 0 0).qubits
      = L * 26 + f
*Worked small instance.** A 4-bit controlled modular adder — 8 Toffolis (`ctl_adder_total_toffolis_n_bit 4`, qianxu p. 22) — on `L` logical patches with a factory of `f` qubits: physical qubits `= L·26 + f`, runtime `= 8·3·cycle = 24·cycle`.
theoremctl_adder4_surface_time
theorem ctl_adder4_surface_time (L f : Nat) (hw : Hardware) :
    (estimateWith (surfaceModel f) hw
        (shorWorkload (ctl_adder_total_toffolis_n_bit 4) L) surface3_qec 0 0).time_us_tenths
      = 8 * 3 * hw.cycle_time_us_tenths

FormalRV.LatticeSurgery.SurfaceSystemCompile

FormalRV/LatticeSurgery/SurfaceSystemCompile.lean
FormalRV.LatticeSurgery.SurfaceSystemCompile — the SYSTEM-LEVEL physical compilation of surface-code Shor, answering the four design questions, and HARDWARE-AGNOSTIC. ## Hardware-agnostic by construction (John 2026-06-02) There is NO `atom` abstraction here. The resource layer is parameterised by a `Hardware` carrying only a cycle time, so it works for superconducting, trapped-ion, OR neutral-atom machines — you plug the cycle time. The system layer (`SysCall`: Gate/Measure/Transit/RequestMagicState/DecodeSyndrome; the `baseInvariants`: capacity, exclusivity, latency, throughput, decoder) is likewise hardware-neutral. HARDWARE-SPECIFIC connectivity/transport enters ONLY as a pluggable `SpaceTimeInvariant` instance (neutral-atom rigid AOD move is one such instance; a superconducting fixed-coupling rule would be another) — it is never part of the core. ## The four questions Q1 (logical→physical map) `patchLo/patchHi/patchZone`: each logical qubit is a disjoint contiguous block of physical qubit sites (`patches_disjoint`). Q2 (ancilla scheduling) `dataSites/syndromeAncilla/routingAncilla`: a patch budgets data + syndrome-extraction + surgery-routing sites (`patch_site_accounts`), tagged as in `AncillaBudget`. Q3 (T-factory scheduling) `magicProducedInWindow/factoryMeetsDemand`: a factory making one magic state per `cyclesPerMagic` with `P` parallel copies; the schedule is valid iff demand ≤ production (`throughputInv`). Q4 (arbitrary distance) `surfaceCodeD d` = [[d²+(d-1)², 1, d]] for ANY d; the resource derivation is distance-parametric (instantiated at d = 27). ## System-level verification `surfaceShorCtx_valid`: a concurrent surface-code Shor schedule (syndrome extraction ∥ surgery merge ∥ magic request ∥ decode ∥ ancilla request) passes `checkAll baseInvariants` — machine-checked, hardware-neutrally. No `sorry`, no new `axiom`.
defsurfaceCodeD
def surfaceCodeD (d : Nat) : FormalRV.Framework.QECCode
The distance-`d` surface code [[d² + (d-1)², 1, d]] for ANY `d`.
theoremsurfaceCodeD_k
theorem surfaceCodeD_k (d : Nat) : (surfaceCodeD d).k = 1
theoremsurfaceCodeD_dist
theorem surfaceCodeD_dist (d : Nat) : (surfaceCodeD d).d = d
theoremsurfaceCodeD_physPer
theorem surfaceCodeD_physPer (d : Nat) :
    physPerLogical (surfaceCodeD d) = (surfaceCodeD d).n
physical/logical for a `k = 1` surface code is its physical-qubit count `n`.
theoremsurface27_is_1405
theorem surface27_is_1405 :
    (surfaceCodeD 27).n = 1405 ∧ (surfaceCodeD 27).d = 27
    ∧ physPerLogical (surfaceCodeD 27) = 1405
*d = 27 instance** — the framework evaluates the real RSA-scale patch: [[1405, 1, 27]], 1405 physical qubits per logical patch.
theoremsurfaceShor_qubits_anyD
theorem surfaceShor_qubits_anyD (d T L factory : Nat) (hw : Hardware) (ow p : Nat) :
    (estimateWith (surfaceModel factory) hw (shorWorkload T L) (surfaceCodeD d) ow p).qubits
      = L * (2 * (surfaceCodeD d).n) + factory
*Distance-general qubit count.** For EVERY distance `d`, the surface-code Shor footprint is `L` patches of `2·n(d)` physical qubits plus the factory.
theoremsurfaceShor_time_anyD
theorem surfaceShor_time_anyD (d T L factory : Nat) (hw : Hardware) (ow p : Nat) :
    (estimateWith (surfaceModel factory) hw (shorWorkload T L) (surfaceCodeD d) ow p).time_us_tenths
      = T * d * hw.cycle_time_us_tenths
*Distance-general runtime.** `T` logical Toffolis, each `d` code cycles.
defpatchSize
def patchSize (d : Nat) : Nat
Physical sites per logical patch: data + an equal standing routing area (`2 · physPerLogical`, the surface convention; gidney-ekera-2021 §2.14).
defpatchLo
def patchLo (i d : Nat) : Nat
First physical-site index of logical qubit `i`.
defpatchHi
def patchHi (i d : Nat) : Nat
One-past-last physical-site index of logical qubit `i`.
theorempatches_disjoint
theorem patches_disjoint (i j d : Nat) (h : i < j) : patchHi i d ≤ patchLo j d
*Q1 layout correctness: distinct logical qubits occupy DISJOINT physical regions.** For `i < j`, qubit `i`'s block ends at or before `j`'s begins.
defdataSites
def dataSites (d : Nat) : Nat
Data sites of a patch (the code's physical-qubit count).
defsyndromeAncilla
def syndromeAncilla (d : Nat) : Nat
In-patch syndrome-extraction ancilla (one basis, qianxu `N = n + (n-k)/2`).
defroutingAncilla
def routingAncilla (d : Nat) : Nat
Standing surgery-routing area (where lattice-surgery merges happen).
theorempatch_site_accounts
theorem patch_site_accounts (d : Nat) :
    patchSize d = dataSites d + routingAncilla d
*Q2 accounting: a patch's sites split into data + surgery-routing.** (Syndrome ancilla are bundled in the in-patch `physPerLogical`, per the surface cost model; the routing area is the equal standing surgery region.)
defmagicProducedInWindow
def magicProducedInWindow (parallelFactories cyclesPerMagic window : Nat) : Nat
Magic states a factory bank produces in a window: `P` parallel copies, each one state per `cyclesPerMagic`, over `window` cycles.
deffactoryMeetsDemand
def factoryMeetsDemand (demand parallelFactories cyclesPerMagic window : Nat) : Bool
The factory bank meets the magic-state demand in the window.
deffactorySites
def factorySites (perFactory parallelFactories : Nat) : Nat
Physical sites of a factory bank: `perFactory` sites × `P` parallel copies.
theoremfactory_meets_demand_demo
theorem factory_meets_demand_demo :
    factoryMeetsDemand 8 4 5 10 = true
*Q3 worked schedule.** A factory making one magic state per 5 cycles, with 4 parallel copies, meets a demand of 8 magic states per 10-cycle window (production = (10/5)·4 = 8).
theoremmagicProduced_mono
theorem magicProduced_mono (P P' cyclesPerMagic window : Nat) (h : P ≤ P') :
    magicProducedInWindow P cyclesPerMagic window
      ≤ magicProducedInWindow P' cyclesPerMagic window
*Monotone in parallelism**: more factory copies never reduce production.
defsurfaceShorSched
def surfaceShorSched : List SysCall
One window of maximally-parallel surface-code Shor work: syndrome extraction (Data) ∥ surgery merge measurement (Workspace) ∥ CCZ magic request for a `teleportCCX` (Factory) ∥ decoder ∥ surgery-ancilla request (Routing).
defsurfaceShorCtx
def surfaceShorCtx : SystemCtx
The surface-code Shor system context (hardware-neutral: `moves := []`).
theoremsurfaceShorCtx_valid
theorem surfaceShorCtx_valid : checkAll baseInvariants surfaceShorCtx = true
*SYSTEM-LEVEL VALIDITY.** The concurrent surface-code Shor schedule passes every base invariant (capacity, exclusivity, latency, throughput, decoder) — machine-checked, hardware-neutrally.
theoremsurfaceShor_anyHardware
theorem surfaceShor_anyHardware (T L factory : Nat) (hw : Hardware) :
    (estimateWith (surfaceModel factory) hw (shorWorkload T L) (surfaceCodeD 27) 0 0).time_us_tenths
      = T * 27 * hw.cycle_time_us_tenths
*Hardware-agnostic resource readout.** The very same distance-`d` derivation holds for ANY `Hardware` — instantiate the cycle time for superconducting, trapped-ion, or neutral-atom. (Here: d = 27, T Toffolis, L patches.)
defhwSuperconducting
def hwSuperconducting : Hardware
defhwTrappedIon
def hwTrappedIon      : Hardware
defhwNeutralAtom
def hwNeutralAtom     : Hardware
example(example)
example (T L f : Nat) :
    (estimateWith (surfaceModel f) hwSuperconducting (shorWorkload T L)
        (surfaceCodeD 27) 0 0).time_us_tenths = T * 27 * 10
Superconducting: runtime `T·27·10` tenths-µs.
example(example)
example (T L f : Nat) :
    (estimateWith (surfaceModel f) hwTrappedIon (shorWorkload T L)
        (surfaceCodeD 27) 0 0).time_us_tenths = T * 27 * 1000
Trapped-ion: the SAME derivation, slower clock → runtime `T·27·1000`.
example(example)
example (T L f : Nat) :
    (estimateWith (surfaceModel f) hwNeutralAtom (shorWorkload T L)
        (surfaceCodeD 27) 0 0).time_us_tenths = T * 27 * 10
Neutral-atom: same framework again.
example(example)
example : checkAll baseInvariants surfaceShorCtx = true
And the SAME concurrent schedule is system-valid regardless of platform — `surfaceShorCtx_valid` does not mention hardware; transport/connectivity is a separate pluggable invariant (neutral-atom rigid move, SC fixed coupling, …).
theoremsurfaceShorCtx_valid_superconducting
theorem surfaceShorCtx_valid_superconducting :
    checkAll (baseInvariants ++ [superconductingFixedCouplingInv]) surfaceShorCtx = true
*Valid on SUPERCONDUCTING hardware**: the schedule carries no `Transport` (`moves := []`), so it satisfies the superconducting fixed-coupling invariant on top of the shared `baseInvariants`.
theoremsurfaceShorCtx_valid_neutralAtom
theorem surfaceShorCtx_valid_neutralAtom :
    checkAll (baseInvariants ++ [neutralAtomRigidMoveInv]) surfaceShorCtx = true
*Valid on NEUTRAL-ATOM hardware**: it also satisfies the neutral-atom rigid-move invariant (vacuously — no transport this window). So one verified surface-code lattice-surgery schedule runs on BOTH platforms.

FormalRV.LatticeSurgery.SurgeryCorrect

FormalRV/LatticeSurgery/SurgeryCorrect.lean
FormalRV.LatticeSurgery.SurgeryCorrect — operational correctness of a qLDPC code-surgery gadget: it implements the logical Pauli measurement of its target operator. This completes Step 2 of the LDPC-PPM plan beyond the operator-support readout of `SurgeryReadout`. Two operational obligations, grounded verbatim in qianxu App. C (`~/Downloads/qianxuLatex/main.tex`): **(R) Eigenvalue extraction** (`main.tex:544`): "the outcomes of the target logical operators ℒ [are] extracted from the parities of the merged-code X-checks in the first stabilizer measurement cycle." Formalized as `surgery_eigenvalue`: the product of the `span_witness`-selected SIGNED merged X-checks equals the target logical operator, signed by the XOR-parity of those checks' outcomes. **(N) Non-disturbance** (`main.tex:544`): the data logical operators that commute with ℒ are preserved ("the k−t logical Z̄ operators of the data code that commute with ℒ"). Formalized as `surgery_preserves_commuting_logical`: any operator commuting with all merged X-checks survives the merge measurement (folded `apply_PPM`). The fault-tolerance triple (`main.tex:435` (i) merged distance Θ(d), (ii) merged qLDPC, (iii) τ_s = Θ(d)) is the delimited residue: (ii)/(iii) are decidable in `LDPCSurgery.verify_surgery_gadget`; the merged distance (i) is the single Cheeger-backed external axiom. No Mathlib. Pure Bool / Nat / List + the PauliString algebra.
defsignedXRow
def signedXRow (s : Bool) (l : BoolVec) : PauliString
An X-type check / logical lowered to a `PauliString`, with phase encoding a measurement outcome (`s = true` ↦ `−1` ↦ `Phase.minus`).
theoremxRow_eq_signedXRow_false
theorem xRow_eq_signedXRow_false (l : BoolVec) : xRow l = signedXRow false l
An unsigned `xRow` is the `s = false` signed row.
theorempmul_xBit_phase
theorem pmul_xBit_phase (a b : Bool) :
    (Pauli.mul (xBit a) (xBit b)).1 = Phase.plus
theoremfoldl_mul_fst
theorem foldl_mul_fst (l : List (Pauli × Pauli)) (ph0 : Phase) (acc0 : List Pauli) :
    (l.foldl
      (fun (acc : Phase × List Pauli) (ab : Pauli × Pauli) =>
        let (a, b)
theoremfoldl_phase_plus
theorem foldl_phase_plus (l : List (Pauli × Pauli)) (ph0 : Phase)
    (hall : ∀ ab ∈ l, (Pauli.mul ab.1 ab.2).1 = Phase.plus) :
    l.foldl (fun (ph : Phase) ab => ph.mul (Pauli.mul ab.1 ab.2).1) ph0 = ph0
If every zipped pair multiplies to phase `+`, the phase fold is the identity on its seed. This is the engine that proves the *only* sign in a product of X/I strings comes from the strings' own phases (their measurement outcomes).
theoremfoldl_phase_plus_xBit
theorem foldl_phase_plus_xBit (a b : BoolVec) :
    ((a.map xBit).zip (b.map xBit)).foldl
        (fun (ph : Phase) ab => ph.mul (Pauli.mul ab.1 ab.2).1) Phase.plus
      = Phase.plus
The phase fold over a zip of `xBit`-lowered lists is trivial, since every X/I single-qubit product carries phase `+` (`pmul_xBit_phase`).
theoremsignedXRow_mul_ops
theorem signedXRow_mul_ops (sa sb : Bool) (a b : BoolVec) (h : a.length = b.length) :
    ((signedXRow sa a).mul (signedXRow sb b)).ops = (xRow (vec_xor a b)).ops
The `.ops` of a product of two signed X-rows is the support-XOR row, identical to the unsigned `xRow` case (phase lives only in `.phase`).
theoremsignedXRow_mul_phase
theorem signedXRow_mul_phase (sa sb : Bool) (a b : BoolVec) :
    ((signedXRow sa a).mul (signedXRow sb b)).phase
      = (if (sa != sb) then Phase.minus else Phase.plus)
The `.phase` of a product of two signed X-rows is the XOR of the two outcome signs: `(-1)^sa · (-1)^sb = (-1)^(sa⊕sb)`. All single-qubit X/I products are phase-trivial, so no extra sign is produced.
theoremsignedXRow_mul
theorem signedXRow_mul (sa sb : Bool) (a b : BoolVec) (h : a.length = b.length) :
    (signedXRow sa a).mul (signedXRow sb b) = signedXRow (sa != sb) (vec_xor a b)
*Signed multiplication law.** Multiplying two signed X-rows XORs both their outcome signs and their supports. This is the algebra that lets a product of measured merged X-checks carry the XOR-parity of their individual ±1 outcomes.
defselectedParity
def selectedParity : BoolVec → List Bool → Bool
  | [],          _       => false
  | _,           []      => false
  | false :: ts, _ :: ss => selectedParity ts ss
  | true :: ts,  s :: ss => s != selectedParity ts ss
The XOR-parity of the outcome signs `ss` over exactly the rows selected by `sel`, mirroring the recursion of `row_combination`.
defselectedSignedProduct
def selectedSignedProduct : BoolVec → BoolMat → List Bool → PauliString
  | [],          _,         _       => xRow []
  | _,           [],        _       => xRow []
  | _,           _,         []      => xRow []
  | false :: ts, _ :: tm,   _ :: ss => selectedSignedProduct ts tm ss
  | true :: ts,  row :: tm, s :: ss =>
      let acc
The signed Pauli-string product of the merged X-checks selected by `sel`, with each selected check carrying its measurement-outcome sign from `ss`. Mirrors `selectedXProduct`/`row_combination` (including the empty-accumulator special case) so all three stay in lockstep.
theoremselectedSignedProduct_ops
theorem selectedSignedProduct_ops (n : Nat) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length →
      (selectedSignedProduct sel mat ss).ops = (xRow (row_combination sel mat)).ops
*Operator-support lockstep for the signed product.** The `.ops` of `selectedSignedProduct` is the lowering of the GF(2) `row_combination` of the same selection — identical to `selectedXProduct_ops`, since the signs live only in `.phase`. Proved by induction mirroring the shared recursion, using `signedXRow_mul_ops` in the key case.
theoremparity_false_of_combo_nil
theorem parity_false_of_combo_nil (n : Nat) (hn : 0 < n) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length → row_combination sel mat = [] →
      selectedParity sel ss = false
When the rows have positive width `n`, an empty GF(2) `row_combination` forces the selected outcome-parity to be `false`: no `true` is selected (a selected positive-width row would make the combination nonempty), so `selectedParity` XORs over the empty selected set. This is the invariant that justifies the empty-accumulator branch of `selectedSignedProduct` discarding the accumulator's (necessarily `+`) sign.
theoremselectedSignedProduct_eq
theorem selectedSignedProduct_eq (n : Nat) (hn : 0 < n) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length →
      selectedSignedProduct sel mat ss
        = signedXRow (selectedParity sel ss) (row_combination sel mat)
*Full lockstep theorem (sign-aware).** The signed product of the `sel`-selected merged X-checks equals the lowering of the GF(2) `row_combination` of the same selection, signed by the XOR-parity of the selected outcome bits. This refines `selectedXProduct_ops` from the operator-support level to the full `PauliString` (phase included). Proved by induction mirroring the shared recursion; the key `true :: ts` case uses `signedXRow_mul` to combine, and `selectedSignedProduct_ops` to detect the empty-accumulator branch (whose parity is pinned to `false` by `parity_false_of_combo_nil`).
theoremsurgery_eigenvalue
theorem surgery_eigenvalue (g : SurgeryGadget) (n : Nat) (hn : 0 < n) (signs : List Bool)
    (hshape : ∀ r ∈ g.merged_hx, r.length = n) (hsig : signs.length = g.merged_hx.length)
    (hker : g.targets_logical_correctly = true) :
    selectedSignedProduct g.span_witness g.merged_hx signs
      = signedXRow (selectedParity g.span_witness signs) g.target_pauli
*Surgery eigenvalue extraction (qianxu App. C, `main.tex:544`).** If the merged X-check matrix is rectangular (all rows of positive width `n`), the outcome-sign list is aligned with it, and the gadget passes its decidable kernel condition `targets_logical_correctly` (qianxu's `⟨ℒ⟩ = f_X'^T ker(H_X'^T)`), then the signed product of the `span_witness`-selected merged X-checks equals the target logical operator `P̄`, signed by the XOR-parity of those checks' measurement outcomes. This is "the outcome of P̄ = parity of the merged X-checks in cycle 1": the operator support is fixed (`surgery_readout_operator`) and the phase carries the XOR of the individual ±1 outcomes.
theoremxBit_commutes
theorem xBit_commutes (x y : Bool) : Pauli.commutes (xBit x) (xBit y) = true
Single-qubit X/I operators always commute: `X/X`, `X/I`, `I/X`, `I/I` are all commuting pairs. This is why any two X-rows commute.
theoremxRow_commutes
theorem xRow_commutes (a b : BoolVec) : (xRow a).commutes (xRow b) = true
*Any two X/I strings commute.** No position of `(xRow a).ops.zip (xRow b).ops` anticommutes (every entry is a pair of `xBit`-images, commuting by `xBit_commutes`), so the anticommuting-position count is `0`, which is even. This is the algebraic basis for the measured merged X-check family being simultaneously measurable.
theoremmerged_X_checks_commute
theorem merged_X_checks_commute (g : SurgeryGadget) :
    ∀ p ∈ merged_stabilizers_X g, ∀ q ∈ merged_stabilizers_X g, p.commutes q = true
*The measured merged X-check family commutes pairwise.** Each element of `merged_stabilizers_X g = g.merged_hx.map xRow` is an `xRow _`, so any two commute by `xRow_commutes`. This certifies the set is a valid simultaneously-measurable commuting family — the precondition for the surgery merge to be a well-defined PPM step.
theoremapply_PPM_pos_preserves_mem_of_commutes
theorem apply_PPM_pos_preserves_mem_of_commutes
    (s : StabilizerState) (P L : PauliString) (hmem : L ∈ s) (hcomm : L.commutes P = true) :
    L ∈ apply_PPM_pos s P
*Core membership preservation under one Gottesman `+`-update.** If `L` is in the stabilizer group `s` and commutes with the measured operator `P`, then `L` is still in `apply_PPM_pos s P`. The Gottesman map replaces the first anticommuting generator by `P`, multiplies the other anticommuting generators by it, and leaves the commuting generators (including `L`) untouched. Concretely: take the index `j` with `s[j]? = some L`; the only branch that would alter `L` is `j = i_anti`, but that would force `L = g_anti`, where `g_anti` anticommutes* with `P` (from the `find_anticommuting` witness), contradicting `L.commutes P = true`. Hence `j ≠ i_anti` and the map sends `(L, j)` to `L`.
defmeasureChecks
def measureChecks (checks : List PauliString) (s : StabilizerState) : StabilizerState
The merge measurement as a left fold of `apply_PPM_pos` over the measured merged X-checks (the first stabilizer cycle of the merge).
theoremmem_measureChecks_of_commutesAll
theorem mem_measureChecks_of_commutesAll (checks : List PauliString) (L : PauliString)
    (s : StabilizerState) (hmem : L ∈ s) (hcomm : ∀ P ∈ checks, L.commutes P = true) :
    L ∈ measureChecks checks s
*Fold preservation.** An operator `L` in `s` that commutes with every* check in `checks` is preserved through the whole folded merge `measureChecks checks s`. Proved by induction on `checks` (generalizing `s`), threading `apply_PPM_pos_preserves_mem_of_commutes` through each step.
theoremsurgery_preserves_commuting_logical
theorem surgery_preserves_commuting_logical (g : SurgeryGadget) (L : PauliString)
    (s : StabilizerState) (hmem : L ∈ s)
    (hcomm : ∀ P ∈ merged_stabilizers_X g, L.commutes P = true) :
    L ∈ measureChecks (merged_stabilizers_X g) s
*Surgery non-disturbance (qianxu App. C, `main.tex:544`).** This is the (N) half of qLDPC code-surgery correctness: any logical operator `L ∈ s` that commutes with all the measured merged X-checks (`merged_stabilizers_X g`) survives the merge measurement — it remains in the post-merge stabilizer group `measureChecks (merged_stabilizers_X g) s`. This is qianxu's "the k−t logical Z̄ operators of the data code that commute with ℒ" are preserved. Combined with `surgery_eigenvalue` (the R half: the readout extracts P̄ signed by the checks' XOR-parity) and `merged_X_checks_commute` (the measured set is a valid simultaneously-measurable commuting family), this gives the full (R ∧ N) logical correctness of the surgery gadget.
defSurgeryFaultTolerant
def SurgeryFaultTolerant (g : SurgeryGadget) (merged_dist : Nat) : Prop
The structural fault-tolerance conditions of qianxu App. C (`main.tex:435`). Of the triple, (ii) the merged code is qLDPC and (iii) `τ_s = Θ(d)` are DECIDABLE and discharged by `verify_surgery_gadget`; (i) the merged-code distance `d̃ = Θ(d)` is the DELIMITED residue, recorded here as the explicit input `merged_dist` with the bound `merged_dist ≥ g.data_code.d`. Its value comes from the boundary Cheeger-constant lower bound for graph ancillas (Swaroop et al.) or a QDistRnd numerical search (per the paper) — it is the single external, non-derived quantity, made structurally visible here rather than baked into a blanket axiom. Crucially, the LOGICAL-correctness theorem `surgery_implements_logical_measurement` below does NOT depend on this: distance governs error SUPPRESSION (fault tolerance under a noise model), not the noiseless logical action. Error suppression and decoder runtime are out of scope per the project taxonomy.
theoremsurgery_implements_logical_measurement
theorem surgery_implements_logical_measurement
    (g : SurgeryGadget) (n : Nat) (signs : List Bool)
    (hn : 0 < n) (hshape : ∀ r ∈ g.merged_hx, r.length = n)
    (hsig : signs.length = g.merged_hx.length)
    (hverify : g.verify_surgery_gadget = true) :
    -- (R) the measured eigenvalue of the target logical = parity of the
    -- selected merged-X-check outcomes
    (selectedSignedProduct g.span_witness g.merged_hx signs
        = signedXRow (selectedParity g.span_witness signs) g.target_pauli)
    -- (N) any logical commuting with the measured set is preserved
    ∧ (∀ (L : PauliString) (s : StabilizerState), L ∈ s →
        (∀ P ∈ merged_stabilizers_X g, L.commutes P = true) →
*A structurally-verified qLDPC code-surgery gadget implements the logical Pauli measurement of its target operator.** Given the decidable structural verifier (`verify_surgery_gadget` = dimensions + qLDPC + τ_s + the kernel condition `⟨ℒ⟩ = f_X'ᵀ ker(H_X'ᵀ)`) and well-shaped merged checks of positive width, the gadget satisfies BOTH halves of surgery correctness: **(R) readout / eigenvalue** — the product of the `span_witness`-selected signed merged X-checks equals the target logical operator signed by the XOR-parity of those checks' ±1 outcomes (qianxu `main.tex:544`: the outcome of `P̄` is the parity of the merged X-checks in the first cycle); **(N) non-disturbance** — every logical commuting with the measured set survives the merge measurement; and the measured set is a valid simultaneously-measurable commuting family. Proved CODE-GENERALLY (any data code) and AXIOM-FREE (only Lean's `propext`/`Classical.choice`/`Quot.sound`; no project axioms, no `sorry`). This is exactly the obligation the sibling QMeas language axiomatizes per code tag (`transversal_X_is_logical_X`); here it is discharged for the qLDPC merged-code construction. Fault tolerance (the merged-distance residue) is delimited separately in `SurgeryFaultTolerant`.
example(example)
example :
    selectedSignedProduct [true, true] [[true, false, true], [false, true, true]]
        [false, true]
      = signedXRow true [true, true, false]
Selecting both rows of a 2×3 merged-X-check matrix with outcomes `(+1, −1)` yields their support-XOR `[X,X,I]` signed by the outcome parity `−1`: `selectedSignedProduct` computes the measured signed operator.
defzRow
def zRow (l : BoolVec) : PauliString
Lower a Z-type check / logical support vector to a `PauliString` (phase `+`; `true ↦ Z`, `false ↦ I`).
theorempmul2_zBit
theorem pmul2_zBit (a b : Bool) : pmul2 (zBit a) (zBit b) = zBit (a != b)
Pointwise: the Z/I product (dropping phase) of two Z-support bits is the XOR of the bits. `Z·Z = I`, `Z·I = Z`, `I·Z = Z`, `I·I = I`.
theoremzipmap_pmul_zBit
theorem zipmap_pmul_zBit (a b : List Bool) (h : a.length = b.length) :
    ((a.map zBit).zip (b.map zBit)).map (fun p => pmul2 p.1 p.2)
      = (vec_xor a b).map zBit
Pure-list core of the Z-type homomorphism: zipping two Z-support lists and taking pointwise products equals XOR-ing then lowering.
theoremzRow_vec_xor_ops
theorem zRow_vec_xor_ops (a b : List Bool) (h : a.length = b.length) :
    ((zRow a).mul (zRow b)).ops = (zRow (vec_xor a b)).ops
*Key homomorphism (Z-type).** GF(2) addition of Z-supports = Pauli multiplication of the corresponding Z-strings, at the operator (`ops`) level.
defmerged_stabilizers_Z
def merged_stabilizers_Z (g : SurgeryGadget) : List PauliString
The Z-type stabilizers of the merged code, lowered to Pauli strings. These are the operators measured during a Z-type surgery merge — the dual of `merged_stabilizers_X`.
defselectedZProduct
def selectedZProduct (sel : List Bool) (mat : BoolMat) : PauliString
The Pauli-string product of the merged Z-checks selected by `sel`, mirroring the recursion of `LDPC.row_combination` — the dual of `selectedXProduct`.
theoremselectedZProduct_ops
theorem selectedZProduct_ops (n : Nat) :
    ∀ (sel : List Bool) (mat : BoolMat), (∀ r ∈ mat, r.length = n) →
      (selectedZProduct sel mat).ops = (zRow (row_combination sel mat)).ops
*Lockstep theorem (Z-type).** The operator support of the `sel`-selected product of merged Z-checks equals the lowering of the GF(2) `row_combination` of the same selection — the dual of `selectedXProduct_ops`.
defsignedZRow
def signedZRow (s : Bool) (l : BoolVec) : PauliString
A Z-type check / logical lowered to a `PauliString`, with phase encoding a measurement outcome (`s = true` ↦ `−1` ↦ `Phase.minus`) — the dual of `signedXRow`.
theoremzRow_eq_signedZRow_false
theorem zRow_eq_signedZRow_false (l : BoolVec) : zRow l = signedZRow false l
An unsigned `zRow` is the `s = false` signed row.
theorempmul_zBit_phase
theorem pmul_zBit_phase (a b : Bool) :
    (Pauli.mul (zBit a) (zBit b)).1 = Phase.plus
theoremfoldl_phase_plus_zBit
theorem foldl_phase_plus_zBit (a b : BoolVec) :
    ((a.map zBit).zip (b.map zBit)).foldl
        (fun (ph : Phase) ab => ph.mul (Pauli.mul ab.1 ab.2).1) Phase.plus
      = Phase.plus
The phase fold over a zip of `zBit`-lowered lists is trivial, since every Z/I single-qubit product carries phase `+` (`pmul_zBit_phase`). The Z-dual of `foldl_phase_plus_xBit`; reuses the generic `foldl_phase_plus`.
theoremsignedZRow_mul_ops
theorem signedZRow_mul_ops (sa sb : Bool) (a b : BoolVec) (h : a.length = b.length) :
    ((signedZRow sa a).mul (signedZRow sb b)).ops = (zRow (vec_xor a b)).ops
The `.ops` of a product of two signed Z-rows is the support-XOR row, identical to the unsigned `zRow` case (phase lives only in `.phase`). The Z-dual of `signedXRow_mul_ops`.
theoremsignedZRow_mul_phase
theorem signedZRow_mul_phase (sa sb : Bool) (a b : BoolVec) :
    ((signedZRow sa a).mul (signedZRow sb b)).phase
      = (if (sa != sb) then Phase.minus else Phase.plus)
The `.phase` of a product of two signed Z-rows is the XOR of the two outcome signs: `(-1)^sa · (-1)^sb = (-1)^(sa⊕sb)`. The Z-dual of `signedXRow_mul_phase`; reuses the generic `foldl_mul_fst`.
theoremsignedZRow_mul
theorem signedZRow_mul (sa sb : Bool) (a b : BoolVec) (h : a.length = b.length) :
    (signedZRow sa a).mul (signedZRow sb b) = signedZRow (sa != sb) (vec_xor a b)
*Signed multiplication law (Z-type).** Multiplying two signed Z-rows XORs both their outcome signs and their supports. The Z-dual of `signedXRow_mul`.
defselectedZParity
def selectedZParity : BoolVec → List Bool → Bool
  | [],          _       => false
  | _,           []      => false
  | false :: ts, _ :: ss => selectedZParity ts ss
  | true :: ts,  s :: ss => s != selectedZParity ts ss
The XOR-parity of the outcome signs `ss` over exactly the rows selected by `sel`, mirroring the recursion of `row_combination` — the Z-dual of `selectedParity`.
defselectedSignedZProduct
def selectedSignedZProduct : BoolVec → BoolMat → List Bool → PauliString
  | [],          _,         _       => zRow []
  | _,           [],        _       => zRow []
  | _,           _,         []      => zRow []
  | false :: ts, _ :: tm,   _ :: ss => selectedSignedZProduct ts tm ss
  | true :: ts,  row :: tm, s :: ss =>
      let acc
The signed Pauli-string product of the merged Z-checks selected by `sel`, with each selected check carrying its measurement-outcome sign from `ss`. The Z-dual of `selectedSignedProduct`.
theoremselectedSignedZProduct_ops
theorem selectedSignedZProduct_ops (n : Nat) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length →
      (selectedSignedZProduct sel mat ss).ops = (zRow (row_combination sel mat)).ops
*Operator-support lockstep for the signed Z-product.** The `.ops` of `selectedSignedZProduct` is the lowering of the GF(2) `row_combination` of the same selection. The Z-dual of `selectedSignedProduct_ops`.
theoremparity_false_of_combo_nil_Z
theorem parity_false_of_combo_nil_Z (n : Nat) (hn : 0 < n) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length → row_combination sel mat = [] →
      selectedZParity sel ss = false
The Z-dual of `parity_false_of_combo_nil`: an empty GF(2) `row_combination` over positive-width rows forces the selected outcome-parity to be `false`.
theoremselectedSignedZProduct_eq
theorem selectedSignedZProduct_eq (n : Nat) (hn : 0 < n) :
    ∀ (sel : BoolVec) (mat : BoolMat) (ss : List Bool), (∀ r ∈ mat, r.length = n) →
      ss.length = mat.length →
      selectedSignedZProduct sel mat ss
        = signedZRow (selectedZParity sel ss) (row_combination sel mat)
*Full lockstep theorem (sign-aware, Z-type).** The signed product of the `sel`-selected merged Z-checks equals the lowering of the GF(2) `row_combination` of the same selection, signed by the XOR-parity of the selected outcome bits. The Z-dual of `selectedSignedProduct_eq`.
theoremsurgery_readout_operator_Z
theorem surgery_readout_operator_Z (g : SurgeryGadget) (n : Nat)
    (zwitness ztarget : BoolVec)
    (hshape : ∀ r ∈ g.merged_hz, r.length = n)
    (hzker : row_combination zwitness g.merged_hz = ztarget) :
    (selectedZProduct zwitness g.merged_hz).ops = (zRow ztarget).ops
*Surgery readout operator (Z-type).** If the merged Z-check matrix is rectangular (all rows of width `n`) and the supplied Z-kernel identity `row_combination zwitness merged_hz = ztarget` holds (the gadget stores only the X-kernel, so this is an explicit hypothesis — the Z-dual of `targets_logical_correctly`), then the product of the `zwitness`-selected merged Z-checks acts, at the operator-support level, as exactly the target logical Z-operator `ztarget`. The Z-dual of `surgery_readout_operator`.
theoremsurgery_eigenvalue_Z
theorem surgery_eigenvalue_Z (g : SurgeryGadget) (n : Nat) (hn : 0 < n)
    (zwitness ztarget : BoolVec) (signs : List Bool)
    (hshape : ∀ r ∈ g.merged_hz, r.length = n) (hsig : signs.length = g.merged_hz.length)
    (hzker : row_combination zwitness g.merged_hz = ztarget) :
    selectedSignedZProduct zwitness g.merged_hz signs
      = signedZRow (selectedZParity zwitness signs) ztarget
*Surgery eigenvalue extraction (Z-type).** The signed product of the `zwitness`-selected merged Z-checks equals the target logical operator `ztarget`, signed by the XOR-parity of those checks' measurement outcomes. The Z-dual of `surgery_eigenvalue`; the Z-kernel identity is supplied as the explicit hypothesis `hzker`.
theoremzBit_commutes
theorem zBit_commutes (x y : Bool) : Pauli.commutes (zBit x) (zBit y) = true
Single-qubit Z/I operators always commute: `Z/Z`, `Z/I`, `I/Z`, `I/I` are all commuting pairs. The Z-dual of `xBit_commutes`.
theoremzRow_commutes
theorem zRow_commutes (a b : BoolVec) : (zRow a).commutes (zRow b) = true
*Any two Z/I strings commute.** The Z-dual of `xRow_commutes`.
theoremmerged_Z_checks_commute
theorem merged_Z_checks_commute (g : SurgeryGadget) :
    ∀ p ∈ merged_stabilizers_Z g, ∀ q ∈ merged_stabilizers_Z g, p.commutes q = true
*The measured merged Z-check family commutes pairwise.** Each element of `merged_stabilizers_Z g = g.merged_hz.map zRow` is a `zRow _`, so any two commute by `zRow_commutes`. The Z-dual of `merged_X_checks_commute`.
theoremsurgery_preserves_commuting_logical_Z
theorem surgery_preserves_commuting_logical_Z (g : SurgeryGadget) (L : PauliString)
    (s : StabilizerState) (hmem : L ∈ s)
    (hcomm : ∀ P ∈ merged_stabilizers_Z g, L.commutes P = true) :
    L ∈ measureChecks (merged_stabilizers_Z g) s
*Surgery non-disturbance (Z-type).** Any logical operator `L ∈ s` that commutes with all the measured merged Z-checks (`merged_stabilizers_Z g`) survives the merge measurement. The Z-dual of `surgery_preserves_commuting_logical`; reuses the generic fold lemma `mem_measureChecks_of_commutesAll` verbatim.
theoremsurgery_implements_logical_measurement_Z
theorem surgery_implements_logical_measurement_Z
    (g : SurgeryGadget) (n : Nat) (zwitness ztarget : BoolVec) (signs : List Bool)
    (hn : 0 < n) (hshape : ∀ r ∈ g.merged_hz, r.length = n)
    (hsig : signs.length = g.merged_hz.length)
    (hzker : row_combination zwitness g.merged_hz = ztarget) :
    -- (R) the measured eigenvalue of the target logical = parity of the
    -- selected merged-Z-check outcomes
    (selectedSignedZProduct zwitness g.merged_hz signs
        = signedZRow (selectedZParity zwitness signs) ztarget)
    -- (N) any logical commuting with the measured set is preserved
    ∧ (∀ (L : PauliString) (s : StabilizerState), L ∈ s →
        (∀ P ∈ merged_stabilizers_Z g, L.commutes P = true) →
*A structurally-verified qLDPC code-surgery gadget implements the logical Z-type Pauli measurement of its target operator** — the Z-type dual of `surgery_implements_logical_measurement`, reading from the merged Z-checks `g.merged_hz` instead of the merged X-checks. Given well-shaped merged Z-checks of positive width and the Z-kernel identity `row_combination zwitness merged_hz = ztarget` (the gadget stores only the X-kernel, so this is an explicit hypothesis), the gadget satisfies BOTH halves of surgery correctness: **(R) readout / eigenvalue** — the product of the `zwitness`-selected signed merged Z-checks equals the target logical operator signed by the XOR-parity of those checks' ±1 outcomes; **(N) non-disturbance** — every logical commuting with the measured set survives the merge measurement; and the measured set is a valid simultaneously-measurable commuting family. Proved CODE-GENERALLY (any data code) and AXIOM-FREE (only Lean's `propext`/`Classical.choice`/`Quot.sound`). Fault tolerance (the merged-distance residue) is delimited separately in `SurgeryFaultTolerant`, exactly as for the X-type theorem.
example(example)
example :
    selectedSignedZProduct [true, true] [[true, false, true], [false, true, true]]
        [false, true]
      = signedZRow true [true, true, false]
Selecting both rows of a 2×3 merged-Z-check matrix with outcomes `(+1, −1)` yields their support-XOR `[Z,Z,I]` signed by the outcome parity `−1`: `selectedSignedZProduct` computes the measured signed operator.

FormalRV.LatticeSurgery.SurgeryDemoCNOT

FormalRV/LatticeSurgery/SurgeryDemoCNOT.lean
FormalRV.LatticeSurgery.SurgeryDemoCNOT — a VERIFIED lattice-surgery CNOT and a VERIFIED CCX (Toffoli) magic injection, both built in the SAME framework (`verify_surgery_gadget` / `verify_surgery_schedule`). Z-type surgery via CSS duality. The framework's verifier checks the X-side row-span (`row_combination span_witness merged_hx = target_pauli`). Measuring Z̄ is the CSS DUAL of measuring X̄: on the dual code `c' = {hx := c.hz, hz := c.hx}`, the logical X̄ of `c'` IS the logical Z̄ of `c`. So a `ZZ`-merge is just an X-surgery gadget on the dual code — the SAME `verify_surgery_gadget`, no new machinery. Results (all by `decide` / `native_decide`, no `sorry`, no `axiom`): surface3_zz_merge — joint Z̄₁Z̄₂ measurement (the CNOT's Z-merge). surface3_cnot — the full CNOT schedule [ZZ-merge, XX-merge]; both merges verified. surface3_zzz_merge — joint Z̄₁Z̄₂Z̄₃ measurement. surface3_ccx_injection — CCX/Toffoli magic injection: assuming a logical |C̄CZ̄⟩ at a PORT patch, the injection is the verified joint Z̄Z̄Z̄ measurement coupling the data to the port (the `measure ZZZ` step of the PPM-level CCX = [useMagicT, measure ZZZ, X-frame]) plus the outcome-controlled Pauli correction. The magic state at the port is an ASSUMED input (not verified-prepared); the teleportation identity it realises is `PPM.CCZGadgetTeleport.ccz_teleport_outcome_000`.
defsurface3x2_dual
def surface3x2_dual : Framework.QECCode
CSS dual of surface3 ⊕ surface3: measuring X̄ of this = measuring Z̄ of the original.
defsurface3x3_dual
def surface3x3_dual : Framework.QECCode
CSS dual of the three-patch code.
defsupp036
def supp036 : BoolVec
surface3 logical Z̄ support {0,3,6} (Z₀Z₃Z₆), length 13.
defsupp_Z1Z2
def supp_Z1Z2 : BoolVec
defsupp_Z1Z2Z3
def supp_Z1Z2Z3 : BoolVec
defsurface3_zz_merge
def surface3_zz_merge : SurgeryGadget
*The ZZ-merge** of a lattice-surgery CNOT: measure the joint logical Z̄₁Z̄₂, built as an X-surgery on the CSS-dual code — discharged by the SAME `verify_surgery_gadget`.
theoremsurface3_zz_merge_verifies
theorem surface3_zz_merge_verifies :
    SurgeryGadget.verify_surgery_gadget surface3_zz_merge = true
theoremsurface3_zz_merge_target_is_logical
theorem surface3_zz_merge_target_is_logical :
    (surface3x2_qec.hx.all (fun r => ! gf2dot r supp_Z1Z2)
      && ! inRowspace surface3x2_qec.hz supp_Z1Z2) = true
Z̄₁Z̄₂ is a genuine joint logical Z: commutes with every X-check, outside the Z-rowspace.
defsurface3_cnot
def surface3_cnot : List SurgeryGadget
The CNOT schedule: a `ZZ`-merge (control–ancilla) then an `XX`-merge (ancilla–target). `surface3_xx_merge` (from `SurgeryDemoMerge`) is reused as the X-merge.
theoremsurface3_cnot_verifies
theorem surface3_cnot_verifies :
    SurgeryGadget.verify_surgery_schedule surface3_cnot = true
*The full lattice-surgery CNOT is verified**: every merge in its schedule passes the framework's structural verifier — a `decide`-checked, axiom-clean CNOT.
defsurface3_zzz_merge
def surface3_zzz_merge : SurgeryGadget
*The joint Z̄₁Z̄₂Z̄₃ measurement** — the `measure ZZZ` of a CCX magic injection.
theoremsurface3_zzz_merge_verifies
theorem surface3_zzz_merge_verifies :
    SurgeryGadget.verify_surgery_gadget surface3_zzz_merge = true
defsurface3_ccx_injection
def surface3_ccx_injection : List SurgeryGadget
theoremsurface3_ccx_injection_verifies
theorem surface3_ccx_injection_verifies :
    SurgeryGadget.verify_surgery_schedule surface3_ccx_injection = true
*The CCX magic-injection measurement is verified** (the joint ZZZ port-merge passes the framework verifier), given the assumed logical magic state at the port.
theoremcnot_and_ccx_injection_verified
theorem cnot_and_ccx_injection_verified :
    SurgeryGadget.verify_surgery_schedule surface3_cnot = true
    ∧ SurgeryGadget.verify_surgery_schedule surface3_ccx_injection = true
*Both a full lattice-surgery CNOT and a CCX magic injection are verified in the same framework** (`verify_surgery_schedule`).

FormalRV.LatticeSurgery.SurgeryDemoMerge

FormalRV/LatticeSurgery/SurgeryDemoMerge.lean
FormalRV.LatticeSurgery.SurgeryDemoMerge — a MULTI-PATCH lattice-surgery gadget on the surface code, verified by the SAME general framework (`verify_surgery_gadget`). Until now every verified `SurgeryGadget` measured ONE logical operator on ONE code patch (surface3, Steane, bbSmall — all single-patch X̄ measurements). This file builds the first MULTI-PATCH gadget: it merges TWO surface [[13,1,3]] patches and measures the JOINT logical X̄₁X̄₂ — i.e. the `XX`-merge that is one of the two merges of a lattice-surgery CNOT. It is NOT a standalone construction: it is an instance of the same `SurgeryGadget` structure, discharged by the same `verify_surgery_gadget` and the same code-general `surgery_implements_logical_measurement`. Data code = surface3 ⊕ surface3 (block-diagonal [[26,2,3]]); logical X̄₁X̄₂ has support {6,7,8} ∪ {19,20,21}; 1 ancilla qubit with 2 X-checks (`H_X' = [[1],[1]]`, a 1-edge tree) coupled by `f_X'` to that joint support; τ_s = 2 (3·2 = 6 ≥ 2·3). The span witness selects the two ancilla merged X-checks whose GF(2) sum is exactly X̄₁X̄₂. No `sorry`, no `axiom`.
defsurface3x2_qec
def surface3x2_qec : Framework.QECCode
surface3 ⊕ surface3: 2 logical qubits, d = 3, parity checks block-diagonal. Patch 1 occupies qubits 0..12, patch 2 occupies qubits 13..25.
defsupp_X1X2
def supp_X1X2 : BoolVec
The joint logical X̄₁X̄₂ support: X̄ on {6,7,8} of patch 1 AND {19,20,21} of patch 2, i.e. `supp678 ++ supp678` over the 26 data qubits.
defsurface3_xx_merge
def surface3_xx_merge : SurgeryGadget
*The XX-merge of a lattice-surgery CNOT**, as a `SurgeryGadget` on surface3 ⊕ surface3. Same shape as the single-patch gadgets: ancilla `H_X' = [[1],[1]]`, `f_X'` couples the ancilla to the joint support {6,7,8,19,20,21}, τ_s = 2; the span witness selects the two ancilla X-checks whose GF(2) sum is X̄₁X̄₂ (extended by 0 on the ancilla).
theoremsurface3_xx_merge_dimensions
theorem surface3_xx_merge_dimensions :
    SurgeryGadget.dimensions_consistent surface3_xx_merge = true
theoremsurface3_xx_merge_tau_s
theorem surface3_xx_merge_tau_s :
    SurgeryGadget.tau_s_sufficient surface3_xx_merge = true
theoremsurface3_xx_merge_qldpc
theorem surface3_xx_merge_qldpc :
    SurgeryGadget.merged_is_qldpc surface3_xx_merge = true
theoremsurface3_xx_merge_targets_correctly
theorem surface3_xx_merge_targets_correctly :
    SurgeryGadget.targets_logical_correctly surface3_xx_merge = true
theoremsurface3_xx_merge_verifies
theorem surface3_xx_merge_verifies :
    SurgeryGadget.verify_surgery_gadget surface3_xx_merge = true
*The two-patch XX-merge passes the framework's complete structural verifier** (dimensions + qLDPC + τ_s = Θ(d) + the row-span kernel condition), `decide` at 27 merged qubits — the SAME `verify_surgery_gadget` used for the single-patch gadgets.
theoremsurface3_xx_merge_target_is_logical
theorem surface3_xx_merge_target_is_logical :
    (surface3x2_qec.hz.all (fun r => ! gf2dot r supp_X1X2)
      && ! inRowspace surface3x2_qec.hx supp_X1X2) = true
*X̄₁X̄₂ is a genuine logical X of surface3 ⊕ surface3**: it commutes with every Z-check (in ker H_Z) and is outside the X-stabilizer rowspace — so the merge measures a real joint logical operator, not an arbitrary Pauli.
theoremsurface3_xx_merge_implements_logical
theorem surface3_xx_merge_implements_logical
    (signs : List Bool) (hsig : signs.length = surface3_xx_merge.merged_hx.length) :
    (selectedSignedProduct surface3_xx_merge.span_witness surface3_xx_merge.merged_hx signs
        = signedXRow (selectedParity surface3_xx_merge.span_witness signs)
            surface3_xx_merge.target_pauli)
    ∧ (∀ (L : PauliString) (s : StabilizerState), L ∈ s →
        (∀ P ∈ merged_stabilizers_X surface3_xx_merge, L.commutes P = true) →
        L ∈ measureChecks (merged_stabilizers_X surface3_xx_merge) s)
    ∧ (∀ p ∈ merged_stabilizers_X surface3_xx_merge, ∀ q ∈ merged_stabilizers_X surface3_xx_merge,
        p.commutes q = true)
*The XX-merge implements the joint logical Pauli measurement of X̄₁X̄₂** (R ∧ N), via the code-general `surgery_implements_logical_measurement` discharged on the two-patch surface code. Same theorem as the single-patch gadgets — this is the general framework, instantiated at a multi-patch merge.
defsurface3x3_qec
def surface3x3_qec : Framework.QECCode
defsupp_X1X2X3
def supp_X1X2X3 : BoolVec
Joint logical X̄₁X̄₂X̄₃ support over the 39 data qubits.
defsurface3_xxx_merge
def surface3_xxx_merge : SurgeryGadget
*A three-patch joint-X̄ surgery gadget** (measures X̄₁X̄₂X̄₃) — the same `SurgeryGadget` framework at 40 merged qubits.
theoremsurface3_xxx_merge_verifies
theorem surface3_xxx_merge_verifies :
    SurgeryGadget.verify_surgery_gadget surface3_xxx_merge = true
*The three-patch joint-X̄ merge passes the same structural verifier** (`native_decide` at 40 merged qubits).
theoremsurface3_xxx_merge_target_is_logical
theorem surface3_xxx_merge_target_is_logical :
    (surface3x3_qec.hz.all (fun r => ! gf2dot r supp_X1X2X3)
      && ! inRowspace surface3x3_qec.hx supp_X1X2X3) = true
X̄₁X̄₂X̄₃ is a genuine joint logical of the three-patch code.

FormalRV.LatticeSurgery.SurgeryDemoSteane

FormalRV/LatticeSurgery/SurgeryDemoSteane.lean
FormalRV.LatticeSurgery.SurgeryDemoSteane — concrete LDPC lattice surgery gadget on Steane [[7,1,3]] code. Demonstrates the surgery infrastructure (`Framework/LDPCMatrix.lean` + `Framework/LDPCSurgery.lean`) on the smallest non-trivial code instance: Data code: Steane [[7, 1, 3]] with explicit parity matrices (Hx = Hz = three weight-4 parity-check rows). Target measurement: logical X̄ on the data qubit, with X̄ = X_3 X_5 X_6 (the standard Steane weight-3 representative). Ancilla: 2 ancilla X-checks on 1 ancilla qubit — a 1-edge tree graph G(V={v_0, v_1}, E={(v_0, v_1)}), satisfying `dim ker H_X'^T = 1` (one connected component). Connection f_X': v_0 connects to data qubits 3, 5, 6 (the support of L̄_X); v_1 connects to no data qubits. τ_s = 2 cycles, giving 3·τ_s = 6 ≥ 2·d = 6 (the FT cycle criterion). The framework verifies: (1) all matrix dimensions consistent; (2) merged code is qLDPC with degree bound 4; (3) τ_s sufficient; (4) target X̄ lies in the row span of merged H̃_X. All four close by `decide`. This is the concrete physical realisation that qianxu's surgery infrastructure makes verifiable. Per the paper (App. C, qianxu): every PPM in the compiled Cuccaro / Shor pipeline is implemented by exactly this kind of surgery gadget (plus a bridge for cross-block PPMs). The framework's verifier discharges the structural correctness condition for each.
defsteane_x_surgery_conn_x
def steane_x_surgery_conn_x : BoolMat
Connection matrix `f_X'`: 2 rows (one per ancilla X-check), each of length 7 (data qubit count). Row 0 = (0,0,0,1,0,1,1) connects v_0 to data qubits 3, 5, 6 (the support of L̄_X). Row 1 = all-zeros: v_1 is a "trivial" boundary vertex with no data attachment.
defsteane_x_surgery_conn_z
def steane_x_surgery_conn_z : BoolMat
Connection matrix `f_Z`: 3 rows (one per data Z-check), each of length 1 (one ancilla qubit). All zeros — for X-type surgery, the ancilla qubit isn't coupled into the data Z-checks.
defsteane_x_surgery_ancilla_hx
def steane_x_surgery_ancilla_hx : BoolMat
Ancilla X-check matrix: 2 rows (one per ancilla X-check S_X'_i), each of length 1 (one ancilla qubit). Both rows have `true` on the ancilla qubit — the tree edge connects both vertices. `H_X' = [[1], [1]]`, so `H_X'^T = [[1, 1]]` and `ker H_X'^T = {(0,0), (1,1)}`, of dimension 1, matching the one-connected-component condition.
defsteane_x_surgery_ancilla_hz
def steane_x_surgery_ancilla_hz : BoolMat
Ancilla Z-check matrix: empty (tree has no cycles ⇒ no Z-stabilisers needed for the ancilla).
defsteane_x_surgery
def steane_x_surgery : SurgeryGadget
The full surgery gadget measuring logical X̄ on Steane.
theoremsteane_x_surgery_dimensions
theorem steane_x_surgery_dimensions :
    SurgeryGadget.dimensions_consistent steane_x_surgery = true
theoremsteane_x_surgery_tau_s
theorem steane_x_surgery_tau_s :
    SurgeryGadget.tau_s_sufficient steane_x_surgery = true
theoremsteane_x_surgery_qldpc
theorem steane_x_surgery_qldpc :
    SurgeryGadget.merged_is_qldpc steane_x_surgery = true
theoremsteane_x_surgery_targets_correctly
theorem steane_x_surgery_targets_correctly :
    SurgeryGadget.targets_logical_correctly steane_x_surgery = true
theoremsteane_x_surgery_verifies
theorem steane_x_surgery_verifies :
    SurgeryGadget.verify_surgery_gadget steane_x_surgery = true
*Headline:** the Steane logical-X̄ surgery gadget passes the framework's complete structural verifier.
defsteane_x_surgery_WRONG
def steane_x_surgery_WRONG : SurgeryGadget
theoremsteane_x_surgery_WRONG_rejected
theorem steane_x_surgery_WRONG_rejected :
    SurgeryGadget.verify_surgery_gadget steane_x_surgery_WRONG = false
defsteane_x_surgery_TAU_TOO_SMALL
def steane_x_surgery_TAU_TOO_SMALL : SurgeryGadget
theoremsteane_x_surgery_TAU_TOO_SMALL_rejected
theorem steane_x_surgery_TAU_TOO_SMALL_rejected :
    SurgeryGadget.verify_surgery_gadget steane_x_surgery_TAU_TOO_SMALL
      = false

FormalRV.LatticeSurgery.SurgeryDemoSurface

FormalRV/LatticeSurgery/SurgeryDemoSurface.lean
FormalRV.LatticeSurgery.SurgeryDemoSurface — a concrete LDPC lattice-surgery gadget on the SURFACE CODE [[13,1,3]] (Path A, John 2026-06-02). This is the first concrete surface-code instantiation of the code-general, axiom-free surgery-correctness theorem `SurgeryCorrect.surgery_implements_logical_measurement`. It closes — for the surface code — the gap John flagged: "we don't know how to implement PPM with a code". The surgery infrastructure was already proven CODE-GENERALLY; what was missing was a verified concrete surface-code `SurgeryGadget`. This file supplies one (X-type, measuring the logical X̄) and connects it to the correctness engine, so "one logical Pauli-product measurement on the surface code is verified-correct". Construction (mirrors `Corpus/SurgeryDemoSteane.lean`): Data code: surface3 = `surfaceHGP 3` = unrotated [[13,1,3]] surface code (6 X-checks, 6 Z-checks), wrapped as a `QECCode` with d = 3, k = 1. Target: logical X̄ = X₆X₇X₈ (the bottom VV-row string), the standard distance-3 surface-code logical-X representative. It commutes with every Z-stabiliser (even overlap) and is not a product of X-stabilisers (the CC qubits cannot cancel to leave {6,7,8}) — a genuine logical. Ancilla: 1 qubit, 2 ancilla X-checks `H_X' = [[1],[1]]` — a 1-edge tree graph (dim ker H_X'ᵀ = 1), exactly as in the Steane demo. Connection f_X': v₀ couples to the X̄ support {6,7,8}; v₁ is trivial. τ_s = 2, giving 3·τ_s = 6 ≥ 2·d = 6. No Mathlib. Pure Bool / Nat / List + decide + the PauliString algebra.
defsurface3_qec
def surface3_qec : QECCode
surface3 ([[13,1,3]]) as the flat `QECCode` the surgery gadget consumes (k = 1, d = 3; hx/hz from the CSS construction).
defsupp678
def supp678 : List Bool
The logical X̄ support `{6,7,8}` as a length-13 Bool vector.
defsurface3_x_surgery_conn_x
def surface3_x_surgery_conn_x : BoolMat
Connection `f_X'`: 2 rows of length 13. Row 0 couples ancilla vertex v₀ to the X̄ support {6,7,8}; row 1 is the trivial vertex v₁.
defsurface3_x_surgery_conn_z
def surface3_x_surgery_conn_z : BoolMat
Connection `f_Z`: 6 rows (one per data Z-check) of length 1, all false (X-type surgery — the ancilla qubit isn't coupled into the data Z-checks).
defsurface3_x_surgery_ancilla_hx
def surface3_x_surgery_ancilla_hx : BoolMat
Ancilla X-checks `H_X' = [[1],[1]]`: 2 checks on 1 ancilla qubit (tree edge).
defsurface3_x_surgery_ancilla_hz
def surface3_x_surgery_ancilla_hz : BoolMat
Ancilla Z-checks: empty (tree has no cycles).
defsurface3_x_surgery
def surface3_x_surgery : SurgeryGadget
The full surgery gadget measuring logical X̄ = X₆X₇X₈ on surface3.
theoremsurface3_x_surgery_dimensions
theorem surface3_x_surgery_dimensions :
    SurgeryGadget.dimensions_consistent surface3_x_surgery = true
theoremsurface3_x_surgery_tau_s
theorem surface3_x_surgery_tau_s :
    SurgeryGadget.tau_s_sufficient surface3_x_surgery = true
theoremsurface3_x_surgery_qldpc
theorem surface3_x_surgery_qldpc :
    SurgeryGadget.merged_is_qldpc surface3_x_surgery = true
theoremsurface3_x_surgery_targets_correctly
theorem surface3_x_surgery_targets_correctly :
    SurgeryGadget.targets_logical_correctly surface3_x_surgery = true
theoremsurface3_x_surgery_verifies
theorem surface3_x_surgery_verifies :
    SurgeryGadget.verify_surgery_gadget surface3_x_surgery = true
*Headline (structural):** the surface3 logical-X̄ surgery gadget passes the framework's complete structural verifier (dimensions + qLDPC + τ_s + the row-span kernel condition).
theoremsurface3_x_surgery_measures_logicalX
theorem surface3_x_surgery_measures_logicalX (signs : List Bool)
    (hsig : signs.length = surface3_x_surgery.merged_hx.length) :
    selectedSignedProduct surface3_x_surgery.span_witness surface3_x_surgery.merged_hx signs
      = signedXRow (selectedParity surface3_x_surgery.span_witness signs)
          surface3_x_surgery.target_pauli
*(R) readout headline: the surface3 surgery gadget MEASURES the logical X̄ = X₆X₇X₈.** The product of the selected signed merged X-checks equals `target_pauli` (the logical X̄) signed by the XOR-parity of those checks' measurement outcomes — i.e. the surgery measures exactly X̄. Axiom-free, via `SurgeryCorrect.surgery_eigenvalue` instantiated at the verified gadget.
theoremsurface3_x_surgery_checks_commute
theorem surface3_x_surgery_checks_commute :
    ∀ p ∈ merged_stabilizers_X surface3_x_surgery,
    ∀ q ∈ merged_stabilizers_X surface3_x_surgery, p.commutes q = true
*(commuting family):** the measured merged X-checks form a valid simultaneously-measurable commuting family — the precondition for the merge to be a well-defined PPM step.
defsurface3_merged_css
def surface3_merged_css : CSSCode
The merged surface3+ancilla code as a `CSSCode` (14 qubits).
theoremsurface3_merged_well_shaped
theorem surface3_merged_well_shaped : surface3_merged_css.well_shaped = true
The merged code is well-shaped and CSS (`H̃_X · H̃_Z^T = 0`). CSS holds precisely because the surgery target is a logical (commutes with all Z-checks).
theoremsurface3_merged_is_CSS
theorem surface3_merged_is_CSS : surface3_merged_css.css_condition = true
theoremsurface3_merged_syndrome_circuit_implements
theorem surface3_merged_syndrome_circuit_implements :
    StabilizerState.valid surface3_merged_css.toStabilizers surface3_merged_css.n = true
*The detailed syndrome-extraction circuit implements the merge.** The lowered merged stabiliser group is a valid (well-sized, pairwise-commuting) stabilizer code — i.e. the physical CSS syndrome circuit of the merged code (one ancilla + CNOTs + measurement per merged check, `CliffordConj`-realised) implements the lattice-surgery merge, via `CSSCode.syndrome_circuit_implements_code`.

FormalRV.LatticeSurgery.SurgeryGadgetToSysCalls

FormalRV/LatticeSurgery/SurgeryGadgetToSysCalls.lean
FormalRV.Framework.SurgeryGadgetToSysCalls — bridge from the EXISTING `LDPCSurgery.SurgeryGadget` IR to a SysCall stream that feeds the strengthened system-layer cert from `LatticeSurgeryPPMContract`. ## Platform-neutral terminology The system layer is **NOT** specific to neutral atoms. A `SiteId` / `PhysicalResourceId` may denote: a superconducting physical qubit, a trapped-ion zone/qubit, a neutral atom, a spin qubit, a qLDPC block position, a lattice-surgery patch slot, or a factory output port, depending on the hardware instantiation. Throughout this file, schedulable-gadget fields use **site** instead of **atom**. ## Legacy-name compatibility Foundational code (e.g., `ScheduleInv.ArchZone.site_lo`, `site_hi`, `total_sites`, `contains_atom`, `Architecture.syscall_acts_on`) predates this terminology fix. Those names are RETAINED to avoid a dangerous global rename; in platform-neutral terminology they should be READ AS site/ physical-resource ids. When this file uses them, comments clarify the platform-neutral reading. ## What this file delivers The first explicit compiler from a lattice-surgery / PPM gadget description to a `List SysCall`, plus an existence theorem that packages the compiled stream as a `PPMScheduleCertWithFactoryPorts` whenever the strengthened invariant bundle holds. ## Reuses (no re-implementation) `SurgeryGadget` from `Framework/LDPCSurgery.lean` (line 99) — the existing L3 qLDPC-surgery IR. Only its `tau_s` (number of merge rounds) is used by the compiler; the structural fields (`data_code`, `ancilla_*`, `conn_*`, `target_pauli`, `span_witness`, `merged_qldpc_bound`) carry the L3 semantic content but are NOT consumed by SysCall compilation here. `PPMScheduleCertWithFactoryPorts` and all combinators from `Framework/LatticeSurgeryPPMContract.lean`: `parSchedules`, `seqManySchedules`, `scheduleWallclockUs`, `mkPPMScheduleCertWithFactoryPorts_of_valid`, `validateScheduleWithFactoryPorts`, `all_invariants_with_factory_ports_ok`. `ppm_block_syscalls` and `ge2021_ppm_arch` from `Framework/GE2021PPMSysInv.lean` — used as the matching-target. ## Verification boundary This file verifies: compilation from L3 surgery-gadget descriptions to SysCall streams; structural equality with the existing hand-written GE2021 PPM block under matching parameters; strengthened system invariants on the compiled stream; derived wallclock/resource values. This file does NOT verify: quantum-semantic correctness of the PPM (whether the lattice surgery actually measures the claimed Pauli product); decoder algorithm correctness; physical derivation of per-SysCall durations; optimal schedule synthesis; full GE2021 schedule at RSA-2048 scale. No Mathlib. Pure Bool / Nat / List. Decidable.
abbrevPhysicalResourceId
abbrev PhysicalResourceId : Type
A generic physical-resource identifier (a qubit, an ion, an atom, a slot — depends on the platform).
abbrevPhysicalQubitId
abbrev PhysicalQubitId    : Type
A physical-qubit identifier.
abbrevSiteId
abbrev SiteId             : Type
A generic site id (a slot in the data/ancilla/factory layout).
abbrevPatchSlotId
abbrev PatchSlotId        : Type
A lattice-surgery patch slot id.
abbrevFactoryPortId
abbrev FactoryPortId      : Type
A factory output port id (a logical "where a magic state appears"; semantics is platform-dependent).
abbrevRoutingSiteId
abbrev RoutingSiteId      : Type
A routing-graph site id.
structureSchedulableSurgeryGadget
structure SchedulableSurgeryGadget
A schedulable wrapper: an existing `SurgeryGadget` plus the timing / physical-resource mapping context the compiler needs. The compiler uses: `gadget.tau_s` — number of stabilizer-extraction rounds. `data_site_a`, `data_site_b` — two representative data sites participating in the joint measurement. (For a full qLDPC surgery the merge stabilizer touches many more; this minimal compiler captures the worst-case per-round resource-traffic pattern.) `ancilla_site` — single ancilla site used across all rounds (each round's `RequestFreshAncilla` re-initialises it). `start_us` — when the gadget's SysCall stream begins. `decoder_id_base` — first decoder id; round `r` uses `decoder_id_base + r`. A `SiteId` here may denote a superconducting physical qubit, a trapped-ion zone/qubit, a neutral atom, a spin qubit, or a lattice-surgery patch slot — depending on the hardware instantiation. See the file header for the platform-neutrality note. For a real `SurgeryGadget` instance the spec must reflect the actual physical-resource layout; this minimal form is enough to populate the strengthened cert.
defcompileSurgeryGadgetRound
def compileSurgeryGadgetRound
    (s : SchedulableSurgeryGadget) (round_idx : Nat) : List SysCall
One round of stabilizer extraction: 5 SysCalls. [t0, t0+1) RequestFreshAncilla [t0+1, t0+2) Gate2q data_a → ancilla [t0+2, t0+3) Gate2q data_b → ancilla [t0+3, t0+4) Measure ancilla [t0+4, t0+5) DecodeSyndrome
defcompileSurgeryGadgetToSysCalls
def compileSurgeryGadgetToSysCalls
    (s : SchedulableSurgeryGadget) : List SysCall
Compile the full gadget: `tau_s` rounds, then one `PauliFrameUpdate` for the final Pauli correction. Total SysCalls = `5 · tau_s + 1`.
theoremcompileSurgeryGadgetRound_length
theorem compileSurgeryGadgetRound_length
    (s : SchedulableSurgeryGadget) (r : Nat) :
    (compileSurgeryGadgetRound s r).length = 5
Each round emits exactly 5 SysCalls.
theoremrounds_flatMap_length
private theorem rounds_flatMap_length (s : SchedulableSurgeryGadget) (n : Nat) :
    ((List.range n).flatMap (compileSurgeryGadgetRound s)).length = 5 * n
The flatMap-over-range part of the compiled stream has length `5 · n` for any `n`. By induction on `n`.
theoremcompileSurgeryGadgetToSysCalls_length
theorem compileSurgeryGadgetToSysCalls_length
    (s : SchedulableSurgeryGadget) :
    (compileSurgeryGadgetToSysCalls s).length = 5 * s.gadget.tau_s + 1
Total SysCall count: `5 · tau_s + 1`.
deftrivial_tau3_gadget
def trivial_tau3_gadget : SurgeryGadget
A trivial `SurgeryGadget` with `tau_s = 3` and otherwise empty fields. Used solely to drive the SysCall compiler structurally — the qLDPC structural verifier passes vacuously on this gadget (empty codes), but the compiler consumes only `tau_s`.
defge2021_basic_ppm_gadget_spec
def ge2021_basic_ppm_gadget_spec : SchedulableSurgeryGadget
The schedulable spec that, when compiled, exactly reproduces `ppm_block_syscalls` (sites 0, 50, 100; start 0; decoder base 0).
theoremcompile_basic_ppm_eq_existing_ppm_block
theorem compile_basic_ppm_eq_existing_ppm_block :
    compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_spec
      = ppm_block_syscalls
*The match theorem (rfl)**: the compiled SysCall stream of the basic GE2021 spec equals the existing `ppm_block_syscalls` definitionally.
theoremcompile_basic_ppm_all_invariants_ok
theorem compile_basic_ppm_all_invariants_ok :
    all_invariants_with_factory_ports_ok
        ge2021_ppm_arch
        (compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_spec)
        10 1000 1000 = true
The compiler preserves the strengthened invariant bundle on the matching spec — reuses the EXISTING `ge2021_ppm_block_factory_exclusivity_ok` + `ppm_block_all_invariants_ok` (after composing with the strengthened bundle). Closed by `native_decide` (small 16-SysCall schedule).
theoremsurgeryGadget_cert_of_valid
theorem surgeryGadget_cert_of_valid
    (arch : ZonedArch) (s : SchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : all_invariants_with_factory_ports_ok arch
           (compileSurgeryGadgetToSysCalls s)
           t_react_us window_us max_per_window = true) :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = arch
      ∧ cert.syscalls = compileSurgeryGadgetToSysCalls s
      ∧ cert.wallclock_us
          = scheduleWallclockUs (compileSurgeryGadgetToSysCalls s)
*Cert constructor for surgery gadgets**: whenever the compiled SysCall stream of a `SchedulableSurgeryGadget` passes the strengthened invariant bundle under the given parameters, a `PPMScheduleCertWithFactoryPorts` exists with matching fields and a derived wallclock. REUSES `mkPPMScheduleCertWithFactoryPorts_of_valid` from `LatticeSurgeryPPMContract.lean` — no duplication of proof unpacking.
theoremge2021_basic_ppm_surgery_cert_exists
theorem ge2021_basic_ppm_surgery_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = ge2021_ppm_arch
      ∧ cert.syscalls
          = compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_spec
Concrete cert existence for the basic GE2021 PPM gadget.
defsurgery_ppm_A
def surgery_ppm_A : SchedulableSurgeryGadget
Good gadget A: data sites 0/50, ancilla site 100, start t=0.
defsurgery_ppm_B_distinct
def surgery_ppm_B_distinct : SchedulableSurgeryGadget
Good gadget B with DISTINCT ancilla (101): for parallel composition.
defsurgery_ppm_C_distinct
def surgery_ppm_C_distinct : SchedulableSurgeryGadget
Good gadget C with another distinct ancilla (102).
defsurgery_ppm_B_alias
def surgery_ppm_B_alias : SchedulableSurgeryGadget
Bad gadget B with the SAME ancilla 100 as A: parallel composition with A causes ancilla aliasing.
theoremsurgery_ppm_A_all_invariants_ok
theorem surgery_ppm_A_all_invariants_ok :
    all_invariants_with_factory_ports_ok ge2021_ppm_arch
        (compileSurgeryGadgetToSysCalls surgery_ppm_A) 10 1000 1000 = true
The good gadget A's compiled stream passes the strengthened bundle under the existing GE2021 architecture. By construction `surgery_ppm_A` is the same spec as the basic GE2021 one.
theoremsurgery_good_cert_exists
theorem surgery_good_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.syscalls = compileSurgeryGadgetToSysCalls surgery_ppm_A
defsurgery_arch
def surgery_arch : ZonedArch
A larger architecture accommodating multiple parallel surgery gadgets. 4 zones × 100 sites each, 400 sites total. Ancilla zone big enough for the 3 ancilla sites used in the triple example. (`total_sites` is the legacy field name on `ScheduleInv.ZonedArch`; read it as "total sites" in platform-neutral terms.)
defsurgery_pair_parallel_alias_syscalls
def surgery_pair_parallel_alias_syscalls : List SysCall
theoremsurgery_pair_parallel_alias_rejected
theorem surgery_pair_parallel_alias_rejected :
    validateScheduleWithFactoryPorts
        surgery_arch surgery_pair_parallel_alias_syscalls 10 1000 1000 = false
The parallel-aliasing surgery pair is REJECTED by the strengthened bundle (Gate2qs in concurrent rounds both claim ancilla 100).
defsurgery_pair_parallel_distinct_syscalls
def surgery_pair_parallel_distinct_syscalls : List SysCall
theoremsurgery_pair_parallel_distinct_all_invariants_ok
theorem surgery_pair_parallel_distinct_all_invariants_ok :
    all_invariants_with_factory_ports_ok surgery_arch
        surgery_pair_parallel_distinct_syscalls 10 1000 1000 = true
theoremsurgery_pair_parallel_distinct_cert_exists
theorem surgery_pair_parallel_distinct_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.syscalls
        = parSchedules
            (compileSurgeryGadgetToSysCalls surgery_ppm_A)
            (compileSurgeryGadgetToSysCalls surgery_ppm_B_distinct)
defsurgery_triple_sequential_syscalls
def surgery_triple_sequential_syscalls : List SysCall
theoremsurgery_triple_sequential_all_invariants_ok
theorem surgery_triple_sequential_all_invariants_ok :
    all_invariants_with_factory_ports_ok surgery_arch
        surgery_triple_sequential_syscalls 10 1000 1000 = true
theoremsurgery_triple_sequential_cert_exists
theorem surgery_triple_sequential_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.syscalls = surgery_triple_sequential_syscalls
theoremsurgery_good_wallclock_is_derived
theorem surgery_good_wallclock_is_derived :
    scheduleWallclockUs (compileSurgeryGadgetToSysCalls surgery_ppm_A)
      = (compileSurgeryGadgetToSysCalls surgery_ppm_A).foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
The good gadget's wallclock IS the foldl of its compiled stream — not a typed-in number.
theoremsurgery_triple_wallclock_is_derived
theorem surgery_triple_wallclock_is_derived :
    scheduleWallclockUs surgery_triple_sequential_syscalls
      = surgery_triple_sequential_syscalls.foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
Same for the triple schedule.
theoremsurgery_good_wallclock_value
theorem surgery_good_wallclock_value :
    scheduleWallclockUs (compileSurgeryGadgetToSysCalls surgery_ppm_A) = 16
Concrete wallclock values for the good gadget and triple.
theoremsurgery_triple_wallclock_value
theorem surgery_triple_wallclock_value :
    scheduleWallclockUs surgery_triple_sequential_syscalls = 48
defrowEdgesAux
def rowEdgesAux (i : Nat) : Nat → BoolVec → List (Nat × Nat)
  | _, []           => []
  | j, true  :: rest => (i, j) :: rowEdgesAux i (j + 1) rest
  | j, false :: rest => rowEdgesAux i (j + 1) rest
Tail-recursive helper: given a row index `i` and a starting column position `j`, walk the BoolVec and emit `(i, k)` for every position `k ≥ j` whose entry is `true`.
defconnEdgesAux
def connEdgesAux : Nat → BoolMat → List (Nat × Nat)
  | _, []           => []
  | i, row :: rest  => rowEdgesAux i 0 row ++ connEdgesAux (i + 1) rest
Walk a `BoolMat` and emit the `(row_idx, col_idx)` pairs of every `true` entry, with row indices starting from `i`.
defconnEdges
def connEdges (conn : BoolMat) : List (Nat × Nat)
Computable edge-list extraction from a connection matrix. Output: every `(i, j)` such that `conn[i][j] = true`, in row-major order.
theoremconnEdges_empty
theorem connEdges_empty : connEdges ([] : BoolMat) = []
The empty connection matrix produces no edges.
structureTopologySchedulableSurgeryGadget
structure TopologySchedulableSurgeryGadget
A TOPOLOGY-aware schedulable wrapper. Unlike `SchedulableSurgeryGadget` (which hard-codes two data sites and one ancilla site), this wrapper carries SITE-MAPPING FUNCTIONS that the compiler applies to the connection-matrix indices to derive the actual physical-resource ids used in each `Gate2q` / `Measure`. Fields: `gadget` — the underlying `SurgeryGadget`. All of its structural fields (`data_code`, `ancilla_n`, `conn_x`, `conn_z`, `tau_s`) are CONSUMED by the compiler. `start_us` — when the gadget's SysCall stream begins. `dataSite : Nat → SiteId` — maps a data-qubit index `j ∈ {0, …, data_code.n - 1}` to its physical-resource id. `ancillaSite : Nat → SiteId` — maps an ancilla-qubit index `i ∈ {0, …, ancilla_n - 1}` to its physical-resource id. `decoderBase : Nat` — first decoder id; round `r` uses `decoderBase + r`. `SiteId` is platform-neutral (see §0).
deftopologyRoundGateCount
def topologyRoundGateCount (s : TopologySchedulableSurgeryGadget) : Nat
Number of `Gate2q` calls one topology round emits = number of `true` entries in `conn_x` plus number of `true` entries in `conn_z`.
deftopologyRoundLength
def topologyRoundLength (s : TopologySchedulableSurgeryGadget) : Nat
Number of SysCalls one topology round emits: 1 RequestFreshAncilla + |edges_x| + |edges_z| + ancilla_n Measures + 1 DecodeSyndrome = `2 + |gates| + ancilla_n`.
defemitXEdgeGates
def emitXEdgeGates
    (s : TopologySchedulableSurgeryGadget)
    (t_start : Nat)
    (edges : List (Nat × Nat)) : List SysCall
Emit a per-edge `Gate2q` SysCall stream for the X-coupling block. An X-edge `(i, j)` (ancilla X-check `i`, data qubit `j`) emits `Gate2q (dataSite j) (ancillaSite i)` at the given offset.
defemitZEdgeGates
def emitZEdgeGates
    (s : TopologySchedulableSurgeryGadget)
    (t_start : Nat)
    (edges : List (Nat × Nat)) : List SysCall
Emit a per-edge `Gate2q` SysCall stream for the Z-coupling block. A Z-edge `(i, j)` (data Z-check `i`, ancilla qubit `j`) emits `Gate2q (dataSite i) (ancillaSite j)` at the given offset. The role of `i`/`j` swaps relative to X-edges because of the asymmetric matrix conventions in `LDPCSurgery.lean`: `conn_x` cols are data, `conn_z` cols are ancilla.
defemitAncillaMeasures
def emitAncillaMeasures
    (s : TopologySchedulableSurgeryGadget) (t_start : Nat) : List SysCall
Emit one `Measure` SysCall per ancilla qubit.
defcompileTopologySurgeryRound
def compileTopologySurgeryRound
    (s : TopologySchedulableSurgeryGadget) (round_idx : Nat) : List SysCall
One topology round emits: [t0, t0+1) RequestFreshAncilla [t0+1, t0+1+|ex|) Gate2q per X-edge [t0+1+|ex|, t0+1+|ex|+|ez|) Gate2q per Z-edge [..|gates|, ..|gates|+a) Measure per ancilla qubit [t0+1+|gates|+a, t0+2+|gates|+a) DecodeSyndrome Total per-round SysCalls = `topologyRoundLength s`.
defcompileTopologySurgeryToSysCalls
def compileTopologySurgeryToSysCalls
    (s : TopologySchedulableSurgeryGadget) : List SysCall
Compile a topology-aware schedulable gadget: `tau_s` rounds, each derived from the actual connection matrices, plus one final `PauliFrameUpdate`.
theoremcompileTopologySurgery_wallclock_is_derived
theorem compileTopologySurgery_wallclock_is_derived
    (s : TopologySchedulableSurgeryGadget) :
    scheduleWallclockUs (compileTopologySurgeryToSysCalls s)
      = (compileTopologySurgeryToSysCalls s).foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
The wallclock of the topology-compiled stream IS the foldl over `end_us` — not a typed-in number.
deftopology_demo_gadget
def topology_demo_gadget : SurgeryGadget
A non-trivial gadget: 2 data qubits, 2 ancilla qubits, one X-coupling edge `(0, 0)` (ancilla X-check #0 ↔ data qubit #0), one Z-coupling edge `(0, 1)` (data Z-check #0 ↔ ancilla qubit #1).
theoremtopology_demo_gadget_verifies
theorem topology_demo_gadget_verifies :
    SurgeryGadget.verify_surgery_gadget topology_demo_gadget = true
The demo gadget passes the EXISTING qLDPC structural verifier from `LDPCSurgery.lean`. Closed by `native_decide` on the small finite structure.
deftopology_demo
def topology_demo : TopologySchedulableSurgeryGadget
The demo schedulable wrapper: data sites 0/1, ancilla sites 100/101, start at t=0, decoder base 0.
theoremtopology_demo_x_edges
theorem topology_demo_x_edges :
    connEdges topology_demo.gadget.conn_x = [(0, 0)]
Edge-list correctness for the X-coupling.
theoremtopology_demo_z_edges
theorem topology_demo_z_edges :
    connEdges topology_demo.gadget.conn_z = [(0, 1)]
Edge-list correctness for the Z-coupling.
theoremtopology_demo_round_length
theorem topology_demo_round_length :
    topologyRoundLength topology_demo = 6
Per-round SysCall count: 1 ancilla request + 1 X-edge gate + 1 Z-edge gate + 2 ancilla measures + 1 decode = 6.
theoremtopology_demo_total_syscalls
theorem topology_demo_total_syscalls :
    (compileTopologySurgeryToSysCalls topology_demo).length = 13
Total SysCall count of the topology-compiled demo: 2 rounds × 6 per-round = 12, plus 1 PauliFrameUpdate.
theoremtopology_demo_all_invariants_with_factory_ports_ok
theorem topology_demo_all_invariants_with_factory_ports_ok :
    all_invariants_with_factory_ports_ok surgery_arch
        (compileTopologySurgeryToSysCalls topology_demo) 10 1000 1000 = true
The topology-compiled demo stream passes the strengthened system-layer invariant bundle on the larger surgery architecture (`surgery_arch`).
theoremtopology_demo_cert_exists
theorem topology_demo_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = surgery_arch
      ∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_demo
Existence of a strengthened cert for the topology-compiled demo schedule.
theoremtopology_demo_wallclock_is_derived
theorem topology_demo_wallclock_is_derived :
    scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo)
      = (compileTopologySurgeryToSysCalls topology_demo).foldl
          (fun acc sc => Nat.max acc sc.end_us) 0
The topology-compiled demo's wallclock is foldl-derived.
theoremtopology_demo_wallclock_value
theorem topology_demo_wallclock_value :
    scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo) = 13
Concrete wallclock value: 6 µs × 2 rounds + 1 µs PauliFrameUpdate = 13.
defverify_surgery_gadget_with_schedule
def verify_surgery_gadget_with_schedule
    (s : TopologySchedulableSurgeryGadget)
    (arch : ZonedArch)
    (t_react_us window_us max_per_window : Nat) : Bool
The combined verifier.
theoremtopology_demo_combined_verifies
theorem topology_demo_combined_verifies :
    verify_surgery_gadget_with_schedule
      topology_demo surgery_arch 10 1000 1000 = true
The demo passes the combined verifier under `(surgery_arch, 10, 1000, 1000)`.
deftopology_demo_alias
def topology_demo_alias : TopologySchedulableSurgeryGadget
A second topology-schedulable gadget with the SAME ancilla sites as `topology_demo`: parallel composition causes ancilla aliasing. Same structural gadget; different start time and decoder base.
deftopology_pair_alias_syscalls
def topology_pair_alias_syscalls : List SysCall
theoremtopology_pair_alias_rejected
theorem topology_pair_alias_rejected :
    validateScheduleWithFactoryPorts
        surgery_arch topology_pair_alias_syscalls 10 1000 1000 = false
The parallel-aliasing topology pair is REJECTED by the strengthened bundle (concurrent rounds both claim ancilla sites 100/101).
deftopology_demo_distinct
def topology_demo_distinct : TopologySchedulableSurgeryGadget
A topology-schedulable gadget with DISTINCT ancilla sites from `topology_demo`: parallel composition is admissible.
deftopology_pair_distinct_syscalls
def topology_pair_distinct_syscalls : List SysCall
theoremtopology_pair_distinct_all_invariants_ok
theorem topology_pair_distinct_all_invariants_ok :
    all_invariants_with_factory_ports_ok surgery_arch
        topology_pair_distinct_syscalls 10 1000 1000 = true
theoremtopology_pair_distinct_cert_exists
theorem topology_pair_distinct_cert_exists :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.syscalls = topology_pair_distinct_syscalls
theoremverify_surgery_gadget_with_schedule_implies_gadget_ok
theorem verify_surgery_gadget_with_schedule_implies_gadget_ok
    (arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : verify_surgery_gadget_with_schedule
            s arch t_react_us window_us max_per_window = true) :
    SurgeryGadget.verify_surgery_gadget s.gadget = true
If the combined checker holds, the underlying `SurgeryGadget` passes the existing qLDPC structural verifier.
theoremverify_surgery_gadget_with_schedule_implies_schedule_ok
theorem verify_surgery_gadget_with_schedule_implies_schedule_ok
    (arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : verify_surgery_gadget_with_schedule
            s arch t_react_us window_us max_per_window = true) :
    SurgeryGadget.verify_surgery_schedule [s.gadget] = true
If the combined checker holds, the underlying gadget — as a one-element schedule — passes the qLDPC schedule verifier. (The schedule verifier just maps `verify_surgery_gadget` over every gadget in the list.)
theoremverify_surgery_gadget_with_schedule_implies_system_ok
theorem verify_surgery_gadget_with_schedule_implies_system_ok
    (arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : verify_surgery_gadget_with_schedule
            s arch t_react_us window_us max_per_window = true) :
    all_invariants_with_factory_ports_ok arch
      (compileTopologySurgeryToSysCalls s)
      t_react_us window_us max_per_window = true
If the combined checker holds, the topology-compiled SysCall stream passes the strengthened system-layer invariant bundle.
theoremverify_surgery_gadget_with_schedule_cert_exists
theorem verify_surgery_gadget_with_schedule_cert_exists
    (arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : verify_surgery_gadget_with_schedule
            s arch t_react_us window_us max_per_window = true) :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = arch
      ∧ cert.syscalls = compileTopologySurgeryToSysCalls s
      ∧ cert.t_react_us = t_react_us
      ∧ cert.window_us = window_us
      ∧ cert.max_per_window = max_per_window
      ∧ cert.wallclock_us
*Main contract theorem.** If the combined checker returns `true` on a topology-schedulable gadget, then a strengthened cert exists with EXACTLY the input parameters and the wallclock derived from the compiled stream by `scheduleWallclockUs`. Reuses `mkPPMScheduleCertWithFactoryPorts_of_valid` — no duplication of the 7-fold invariant unpacking.
theoremverify_surgery_gadget_with_schedule_sound
theorem verify_surgery_gadget_with_schedule_sound
    (arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
    (t_react_us window_us max_per_window : Nat)
    (h : verify_surgery_gadget_with_schedule
            s arch t_react_us window_us max_per_window = true) :
    SurgeryGadget.verify_surgery_gadget s.gadget = true
    ∧ SurgeryGadget.verify_surgery_schedule [s.gadget] = true
    ∧ all_invariants_with_factory_ports_ok arch
        (compileTopologySurgeryToSysCalls s)
        t_react_us window_us max_per_window = true
    ∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
        cert.syscalls = compileTopologySurgeryToSysCalls s
*The paper-facing contract theorem.** If the combined Boolean checker returns `true`, then: (1) the qLDPC `SurgeryGadget` passes the existing structural verifier; (2) the same gadget — as a one-element schedule — passes the qLDPC schedule verifier; (3) the topology-compiled SysCall stream passes the strengthened system-layer invariant bundle (I1-I4 + factory-port exclusivity); AND (4) a `PPMScheduleCertWithFactoryPorts` exists whose `syscalls` field is exactly the compiled stream.
deftopology_demo_arch
def topology_demo_arch : ZonedArch
The demo architecture — alias for `surgery_arch`. Stated as a separate `def` so the demo theorems quote a "demo-named" parameter rather than the generic `surgery_arch`.
deftopology_demo_t_react_us
def topology_demo_t_react_us : Nat
Standard decoder-react budget for the demos: 10 µs.
deftopology_demo_window_us
def topology_demo_window_us : Nat
Standard throughput window for the demos: 1000 µs.
deftopology_demo_max_per_window
def topology_demo_max_per_window : Nat
Standard max syscalls per window for the demos.
theoremtopology_demo_combined_verifies_alias
theorem topology_demo_combined_verifies_alias :
    verify_surgery_gadget_with_schedule
      topology_demo topology_demo_arch
      topology_demo_t_react_us topology_demo_window_us
      topology_demo_max_per_window = true
The topology demo passes the combined verifier under the demo parameters. Re-stated from `topology_demo_combined_verifies` so it quotes the demo aliases rather than the literals.
theoremtopology_demo_sound
theorem topology_demo_sound :
    SurgeryGadget.verify_surgery_gadget topology_demo.gadget = true
    ∧ SurgeryGadget.verify_surgery_schedule [topology_demo.gadget] = true
    ∧ all_invariants_with_factory_ports_ok topology_demo_arch
        (compileTopologySurgeryToSysCalls topology_demo)
        topology_demo_t_react_us topology_demo_window_us
        topology_demo_max_per_window = true
    ∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
        cert.syscalls = compileTopologySurgeryToSysCalls topology_demo
*Demo instantiation of the bundled contract theorem.**
theoremtopology_demo_cert_from_combined_verifier
theorem topology_demo_cert_from_combined_verifier :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = topology_demo_arch
      ∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_demo
      ∧ cert.wallclock_us
          = scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo)
*Demo cert extraction**: the topology demo yields a strengthened cert whose wallclock is derived from its compiled stream.
deftopology_steane_x
def topology_steane_x : TopologySchedulableSurgeryGadget
The Steane X-surgery gadget wrapped as a topology schedulable. Reuses `Corpus.SurgeryDemoSteane.steane_x_surgery`.
theoremtopology_steane_x_x_edges
theorem topology_steane_x_x_edges :
    connEdges topology_steane_x.gadget.conn_x = [(0, 3), (0, 5), (0, 6)]
Edge-count sanity: the Steane X-surgery has 3 X-edges (row 0 of `conn_x` touches data qubits 3, 5, 6; row 1 is all-zero) and 0 Z-edges (the Z-coupling matrix is all false). Closed by `decide` since `topology_steane_x` and its underlying gadget are `def`s (no `@[reducible]`); both sides are concrete and decidable.
theoremtopology_steane_x_z_edges
theorem topology_steane_x_z_edges :
    connEdges topology_steane_x.gadget.conn_z = []
theoremtopology_steane_x_round_length
theorem topology_steane_x_round_length :
    topologyRoundLength topology_steane_x = 6
Per-round SysCall count: 1 ancilla request + 3 X-edge gates + 0 Z-edge gates + 1 ancilla measure + 1 decode = 6.
theoremtopology_steane_x_combined_verifies
theorem topology_steane_x_combined_verifies :
    verify_surgery_gadget_with_schedule
      topology_steane_x topology_demo_arch
      topology_demo_t_react_us topology_demo_window_us
      topology_demo_max_per_window = true
The Steane topology gadget passes the combined verifier on `topology_demo_arch`.
theoremtopology_steane_x_sound
theorem topology_steane_x_sound :
    SurgeryGadget.verify_surgery_gadget topology_steane_x.gadget = true
    ∧ SurgeryGadget.verify_surgery_schedule [topology_steane_x.gadget] = true
    ∧ all_invariants_with_factory_ports_ok topology_demo_arch
        (compileTopologySurgeryToSysCalls topology_steane_x)
        topology_demo_t_react_us topology_demo_window_us
        topology_demo_max_per_window = true
    ∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
        cert.syscalls = compileTopologySurgeryToSysCalls topology_steane_x
*Corpus instantiation of the bundled contract theorem.**
theoremtopology_steane_x_cert_from_combined_verifier
theorem topology_steane_x_cert_from_combined_verifier :
    ∃ cert : PPMScheduleCertWithFactoryPorts,
      cert.arch = topology_demo_arch
      ∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_steane_x
      ∧ cert.wallclock_us
          = scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_steane_x)
*Corpus cert extraction.**
theoremtopology_alias_pair_system_not_ok
theorem topology_alias_pair_system_not_ok :
    all_invariants_with_factory_ports_ok
        topology_demo_arch topology_pair_alias_syscalls
        topology_demo_t_react_us topology_demo_window_us
        topology_demo_max_per_window = false

FormalRV.LatticeSurgery.SurgeryReadout

FormalRV/LatticeSurgery/SurgeryReadout.lean
FormalRV.Framework.SurgeryReadout — Step 2 of the LDPC-PPM correctness plan (`notes/topic-ldpc-ppm-correctness.md`): the READOUT bridge from the decidable kernel condition of a qLDPC code-surgery gadget to the Pauli-operator statement "the product of the measured merged X-checks equals the target logical Pauli". ## Where this sits `LDPCSurgery.SurgeryGadget` carries the merged-code parity matrices `merged_hx`/`merged_hz` (qianxu App. C, `main.tex:425`) and the decidable structural verifier `verify_surgery_gadget`, whose load-bearing clause is the kernel condition `targets_logical_correctly : row_combination span_witness merged_hx = target_pauli` (i.e. qianxu's `⟨ℒ⟩ = f_X'^T ker(H_X'^T)`, restated as a GF(2) row-span identity). That clause is a fact about *bit vectors*. This file lifts it to a fact about *Pauli operators*: under the lowering `xRow` (X-support bitvector ↦ X-type PauliString), GF(2) addition of supports IS Pauli multiplication (`xRow_vec_xor_ops`), so the row-span identity says exactly that the product of the `span_witness`-selected merged X-checks acts as the target logical X-operator `P̄`. This is the "back-end realization obligation" that the QMeas measurement language (sibling paper) takes as the axiom `transversal_X_is_logical_X` — here PROVED for the qLDPC merged-code construction, code-generally (any data code). Scope of THIS slice: the operator-support (`.ops`) statement — i.e. *which* logical Pauli is measured. The eigenvalue-extraction (folding `apply_PPM` over the merged stabilizers, using the `PPMUpdateInvariants` lemmas) and non-disturbance are the next slice. Phase/sign is +1 for X-type CSS checks; tracked separately. No Mathlib. Pure Bool / Nat / List + the PauliString algebra.
defxRow
def xRow (l : List Bool) : PauliString
Lower an X-type check / logical support vector to a `PauliString` (phase `+`; `true ↦ X`, `false ↦ I`).
theorempmul2_xBit
theorem pmul2_xBit (a b : Bool) : pmul2 (xBit a) (xBit b) = xBit (a != b)
Pointwise: the X/I product (dropping phase) of two X-support bits is the XOR of the bits. `X·X = I`, `X·I = X`, `I·X = X`, `I·I = I`.
theoremzipmap_pmul_xBit
theorem zipmap_pmul_xBit (a b : List Bool) (h : a.length = b.length) :
    ((a.map xBit).zip (b.map xBit)).map (fun p => pmul2 p.1 p.2)
      = (vec_xor a b).map xBit
Pure-list core of the homomorphism: zipping two X-support lists and taking pointwise products equals XOR-ing then lowering.
theoremxRow_vec_xor_ops
theorem xRow_vec_xor_ops (a b : List Bool) (h : a.length = b.length) :
    ((xRow a).mul (xRow b)).ops = (xRow (vec_xor a b)).ops
*Key homomorphism.** GF(2) addition of X-supports = Pauli multiplication of the corresponding X-strings, at the operator (`ops`) level. This is what makes the kernel condition a statement about the measured logical operator.
defmerged_stabilizers_X
def merged_stabilizers_X (g : SurgeryGadget) : List PauliString
The X-type stabilizers of the merged code, lowered to Pauli strings. These are the operators measured during the surgery merge (qianxu App. C step 2).
defselectedXProduct
def selectedXProduct (sel : List Bool) (mat : BoolMat) : PauliString
The Pauli-string product of the merged X-checks selected by `sel`, mirroring the recursion of `LDPC.row_combination` (including its empty-accumulator special case) so the two stay in lockstep.
theoremvec_xor_length
theorem vec_xor_length (a b : BoolVec) :
    (vec_xor a b).length = min a.length b.length
Componentwise XOR truncates to the shorter operand, so its length is the `min` of the two input lengths. Needed below to discharge the `length`-equality side condition of `zipmap_pmul_xBit`.
theoremrow_combination_length
theorem row_combination_length (n : Nat) :
    ∀ (sel : List Bool) (mat : BoolMat), (∀ r ∈ mat, r.length = n) →
      (row_combination sel mat = [] ∨ (row_combination sel mat).length = n)
A `row_combination` over a rectangular matrix (every row of length `n`) is either empty (no rows selected, or empty selection/matrix) or itself of length `n`. This is the shape invariant that lets the `selectedXProduct`/`row_combination` lockstep proof feed a `length`-matched pair into the GF(2)→Pauli homomorphism.
theoremselectedXProduct_ops
theorem selectedXProduct_ops (n : Nat) :
    ∀ (sel : List Bool) (mat : BoolMat), (∀ r ∈ mat, r.length = n) →
      (selectedXProduct sel mat).ops = (xRow (row_combination sel mat)).ops
*Lockstep theorem.** The operator support of the `sel`-selected product of merged X-checks equals the lowering of the GF(2) `row_combination` of the same selection. Proved by induction mirroring the shared recursion of `selectedXProduct` and `row_combination`; the key `true :: ts, row :: tm` case uses the GF(2)→Pauli homomorphism `xRow_vec_xor_ops` together with the `row_combination_length` shape invariant to discharge the `length`-matched side condition.
theoremsurgery_readout_operator
theorem surgery_readout_operator (g : SurgeryGadget) (n : Nat)
    (hshape : ∀ r ∈ g.merged_hx, r.length = n)
    (hker : g.targets_logical_correctly = true) :
    (selectedXProduct g.span_witness g.merged_hx).ops = (xRow g.target_pauli).ops
*Surgery readout operator.** If the merged X-check matrix is rectangular (all rows of width `n`) and the gadget passes its decidable kernel condition `targets_logical_correctly` (qianxu's `⟨ℒ⟩ = f_X'^T ker(H_X'^T)`, restated as a GF(2) row-span identity), then the product of the `span_witness`-selected merged X-checks acts, at the operator-support level, as exactly the target logical X-operator `P̄`. This is the "back-end realization obligation" that the QMeas measurement language axiomatizes as `transversal_X_is_logical_X`; here it is PROVED for the qLDPC merged-code construction, code generally (for any data code, any rectangular merged `H_X`).
example(example)
example : row_combination [true, true] [[true, false, true], [false, true, true]]
    = [true, true, false]
GF(2) selection of both rows of a 2×3 X-check matrix: the row span of `[[X·X], …]` selected by `[true,true]` is the componentwise XOR `vec_xor [T,F,T] [F,T,T] = [T,T,F]`.
example(example)
example : (selectedXProduct [true, true] [[true, false, true], [false, true, true]]).ops
    = (xRow [true, true, false]).ops
The Pauli-string product computed by `selectedXProduct` over the same selection has exactly the operator support of the lowered XOR vector `xRow [T,T,F] = X⊗X⊗I`. Demonstrates `selectedXProduct` realizes the row-span product correctly on a concrete instance.

FormalRV.LatticeSurgery.SurgeryReduction

FormalRV/LatticeSurgery/SurgeryReduction.lean
FormalRV.LatticeSurgery.SurgeryReduction — the OPERATIONAL reduction: a logical Pauli-product-measurement command reduces to running the surgery gadget as a concrete stabilizer PROGRAM (a "surgery schedule"). Path A, step (1) (John 2026-06-02). `SurgeryCorrect.surgery_implements_logical_ measurement` already proves, axiom-free and code-generally, the OPERATOR-level facts (R) eigenvalue extraction + (N) non-disturbance + commuting family. Here we LIFT that from a static operator identity to a STATE-TRANSFORMATION property of an actual PPM PROGRAM EXECUTION: the surgery merge, written as a `StabProgram` (one `StabOp.meas` per merged X-check) and run by `StabProgram.runProgram`, induces the merge state-map `measureChecks`, and the readout (R) / non- disturbance (N) hold OF THAT EXECUTION. We choose the SIMPLEST CORRECT schedule — one measurement per merged check, the all-`+1` outcome branch — not an optimized minimum-space-time-volume schedule (John 2026-06-02: correctness first; the optimized schedule, when supplied, is verified by the SAME `verify_surgery_gadget` + this reduction, since both are code- and gadget-general). ## What is GENUINELY NEW vs reused (honesty, per CLAUDE.md) NEW (the only new operational content): `runProgram_map_meas_nil` / `surgery_schedule_runs_as_merge` — running the merge schedule as a program EQUALS the `measureChecks` state-map. This makes "running the surgery gadget" a first-class program execution (a peer of `hProgram`/`cnotProgram` in `StabProgram`), not a bare fold. REUSED: (R) from `surgery_implements_logical_measurement`.1; (N) from `surgery_preserves_commuting_logical`. The lift re-exposes these as properties of `runProgram …`. ## Honest residue (stays a CONTRACT — NOT closed here) This is the STABILIZER-LAYER reduction. It does NOT reach `ShorPPMEndToEnd`, whose `MagicBasisPPMState` carries a PURELY CLASSICAL `bits : Nat → Bool` semantics (a `measurePauliKind Z` there is a deterministic bit-flip macro, NOT a projective ±1 measurement). Connecting the two needs the Gottesman–Knill refinement (computational bits = the +1 sector of a stabilizer state) — a separate multi-step bridge, left explicit. Also out of scope: (i) the full-state equality `measureChecks … = apply_PPM_pos s (xRow target)`, which is FALSE as a raw equality (the merged code has more qubits than the data code; they coincide only after the unformalized ancilla detach/projection, qianxu App. C Step 3); (ii) `teleportCCX` (non-Clifford, no stabilizer semantics); (iii) merged-code distance / fault tolerance. No Mathlib. Pure List / the PauliString algebra + the Gottesman update. No `sorry`, no `axiom`.
theoremrunProgram_map_meas_nil
theorem runProgram_map_meas_nil (checks : List PauliString) (s : StabilizerState) :
    runProgram (checks.map StabOp.meas) [] s
      = checks.foldl (fun st P => apply_PPM_pos st P) s
Running a sequence of `StabOp.meas` operations on the all-`+1` outcome branch (the empty outcome list) is exactly the left fold of the Gottesman `+`-update `apply_PPM_pos` — i.e. `StabProgram.runProgram` of a pure measurement schedule is `SurgeryCorrect.measureChecks`'s engine. Proven by induction.
theoremsurgery_schedule_runs_as_merge
theorem surgery_schedule_runs_as_merge (g : SurgeryGadget) (s : StabilizerState) :
    runProgram ((merged_stabilizers_X g).map StabOp.meas) [] s
      = measureChecks (merged_stabilizers_X g) s
*Schedule = merge.** The surgery merge, written as the concrete stabilizer program `(merged X-checks).map StabOp.meas` and executed by `runProgram` on the all-`+1` branch, induces exactly the merge state-map `measureChecks (merged_stabilizers_X g)`. This is what makes "running the surgery gadget" a genuine PPM-PROGRAM EXECUTION.
theoremlogical_PPM_reduces_to_surgery_schedule
theorem logical_PPM_reduces_to_surgery_schedule
    (g : SurgeryGadget) (n : Nat) (signs : List Bool)
    (hn : 0 < n) (hshape : ∀ r ∈ g.merged_hx, r.length = n)
    (hsig : signs.length = g.merged_hx.length)
    (hverify : g.verify_surgery_gadget = true) :
    -- (SCHEDULE) the surgery schedule-program IS the merge state-map
    (∀ s, runProgram ((merged_stabilizers_X g).map StabOp.meas) [] s
            = measureChecks (merged_stabilizers_X g) s)
    -- (R) its readout extracts P̄ signed by the merged-check outcome parity
    ∧ (selectedSignedProduct g.span_witness g.merged_hx signs
            = signedXRow (selectedParity g.span_witness signs) g.target_pauli)
    -- (N) it preserves the logical sector commuting with P̄ (of the EXECUTION)
*The logical Pauli-product-measurement command reduces to the surgery schedule.** For a structurally-verified gadget, the abstract command "measure the logical operator P̄ = `target_pauli`" is realised by executing the surgery schedule-program, which: (SCHEDULE) IS the merge state-map `measureChecks` (the new operational identity `surgery_schedule_runs_as_merge`); (R) reads out P̄ signed by the XOR-parity of the merged-check outcomes (reused from `surgery_implements_logical_measurement`); (N) preserves every logical commuting with the measured set — now as a property of the PROGRAM EXECUTION `runProgram …`, not just the bare fold. This is strictly more than the operator identity: it certifies that the abstract measurement command and the concrete schedule-program induce the same state map on the relevant sector. Axiom-free.
theoremsurgery_schedule_runs_as_merge_Z
theorem surgery_schedule_runs_as_merge_Z (g : SurgeryGadget) (s : StabilizerState) :
    runProgram ((merged_stabilizers_Z g).map StabOp.meas) [] s
      = measureChecks (merged_stabilizers_Z g) s
theoremlogical_PPM_Z_reduces_to_surgery_schedule
theorem logical_PPM_Z_reduces_to_surgery_schedule
    (g : SurgeryGadget) (n : Nat) (zwitness ztarget : BoolVec) (signs : List Bool)
    (hn : 0 < n) (hshape : ∀ r ∈ g.merged_hz, r.length = n)
    (hsig : signs.length = g.merged_hz.length)
    (hzker : row_combination zwitness g.merged_hz = ztarget) :
    (∀ s, runProgram ((merged_stabilizers_Z g).map StabOp.meas) [] s
            = measureChecks (merged_stabilizers_Z g) s)
    ∧ (selectedSignedZProduct zwitness g.merged_hz signs
            = signedZRow (selectedZParity zwitness signs) ztarget)
    ∧ (∀ (L : PauliString) (s : StabilizerState), L ∈ s →
         (∀ P ∈ merged_stabilizers_Z g, L.commutes P = true) →
         L ∈ runProgram ((merged_stabilizers_Z g).map StabOp.meas) [] s)
The Z-type logical PPM command (measuring the logical Z̄ = `ztarget`) reduces to the merged-Z-check surgery schedule-program, with readout (R) + non- disturbance (N) of the execution. `zwitness/ztarget` carry the Z-kernel identity (the gadget stores only the X-kernel), as in `surgery_implements_logical_measurement_Z`.
example(example)
example (s : StabilizerState) :
    runProgram ([xRow [true, false], xRow [false, true]].map StabOp.meas) [] s
      = measureChecks [xRow [true, false], xRow [false, true]] s

FormalRV.LatticeSurgery.SurgerySchedule

FormalRV/LatticeSurgery/SurgerySchedule.lean
FormalRV.Framework.SurgerySchedule — from ONE surgery to a WHOLE SCHEDULE. `SurgeryReduction` / `ZXStabilizer` proved that a SINGLE logical Pauli-product measurement, expressed in the ZX IR, runs as one surgery merge (`mergeZX_X_runs_as_surgery`). A full fault-tolerant computation — e.g. Shor's modular exponentiation — is a SEQUENCE of such logical PPMs. This module lifts the single-merge reduction to an arbitrary SCHEDULE (a list of surgery gadgets), proving that the composed ZX/PPM program of the whole schedule runs EXACTLY as the sequence of surgery merges on the stabilizer state: zxRun (scheduleProgramX sched) s = runScheduleX sched s. This is the operational core of the capstone's deferred contract "enumerate all of Shor's PPMs into one composed surface schedule" (`SurfaceShorPPMEndToEnd`), discharged at the stabilizer-state level for an arbitrary-length schedule. The proof rests on one new structural fact — `zxRun` distributes over diagram concatenation (`zxRun_append`) — plus the per-merge reduction, by induction on the schedule. Both bases (X and Z) are covered. No Mathlib. No `sorry`, no `axiom`.
theoremzxRun_eq_foldl
theorem zxRun_eq_foldl (d : ZXDiagram) (s : StabilizerState) :
    zxRun d s = (d.map ZXSpider.toPauli).foldl (fun st P => apply_PPM_pos st P) s
The all-`+1` ZX run is the left fold of `apply_PPM_pos` over the measured Paulis — the same fold `measureChecks` uses.
theoremzxRun_append
theorem zxRun_append (d1 d2 : ZXDiagram) (s : StabilizerState) :
    zxRun (d1 ++ d2) s = zxRun d2 (zxRun d1 s)
*`zxRun` distributes over diagram concatenation.** Running `d₁ ++ d₂` is running `d₂` on the state produced by running `d₁` — sequential composition of PPM programs.
abbrevSchedule
abbrev Schedule
A surface-code lattice-surgery SCHEDULE: a list of surgery gadgets executed in order (each one logical Pauli-product measurement).
defscheduleProgramX
def scheduleProgramX (sched : Schedule) : ZXDiagram
The whole schedule's composed ZX/PPM program: concatenate each gadget's X-merge diagram.
defrunScheduleX
def runScheduleX (sched : Schedule) (s : StabilizerState) : StabilizerState
The schedule's intended state map: apply each gadget's surgery merge (`measureChecks`) in order.
theoremschedule_runs_as_surgeries
theorem schedule_runs_as_surgeries (sched : Schedule) (s : StabilizerState) :
    zxRun (scheduleProgramX sched) s = runScheduleX sched s
*WHOLE-SCHEDULE REDUCTION (X-type).** The composed ZX/PPM program of an arbitrary-length surface-code schedule runs exactly as the sequence of surgery merges — many logical PPMs enumerated into one composed surface schedule, verified at the stabilizer-state level. Axiom-free.
defscheduleProgramZ
def scheduleProgramZ (sched : Schedule) : ZXDiagram
The whole schedule's composed Z-merge program.
defrunScheduleZ
def runScheduleZ (sched : Schedule) (s : StabilizerState) : StabilizerState
The schedule's Z-merge state map.
theoremschedule_runs_as_surgeries_Z
theorem schedule_runs_as_surgeries_Z (sched : Schedule) (s : StabilizerState) :
    zxRun (scheduleProgramZ sched) s = runScheduleZ sched s
*WHOLE-SCHEDULE REDUCTION (Z-type).**
defscheduleTotalRounds
def scheduleTotalRounds (sched : Schedule) : Nat
Total syndrome rounds of the schedule (sum of each merge's verified `tau_s`).
example(example)
example (g h : SurgeryGadget) :
    scheduleTotalRounds [g, h] = g.tau_s + h.tau_s
A two-surgery schedule's rounds add: smoke that the aggregate composes.