FormalRV

PPM 1103 declarations in 48 modules

FormalRV.PPM.CCZGadgetTeleport

FormalRV/PPM/CCZGadgetTeleport.lean
FormalRV.PPM.CCZGadgetTeleport — measurement-based gate teleportation for the CCZ gate, all-zeros (b=000) measurement branch, proved correct on state vectors. The 3-qubit analogue of MagicStateTeleport's `t_teleport_outcome_0` (the no-correction T branch). ## The protocol (one branch) To apply CCZ to a 3-qubit data register |ψ⟩ using one |CCZ⟩ = CCZ·|+++⟩ magic state: 1. prepare |ψ⟩ ⊗ |CCZ⟩ (3 data ⊗ 3 ancilla = 6 qubits, 64-dim space); 2. apply the transversal CNOT chain (data qubit k controls ancilla k); 3. measure all three ancillas in the Z basis; outcome 000 ⇒ the data register is CCZ·|ψ⟩ (no correction) — PROVED HERE; outcomes 001..111 ⇒ outcome-dependent CZ/Pauli correction — NOT formalised here. ## Honesty boundary (see `honest_gaps`) State-vector correctness of the 000 branch only; the 1/(2√2) factor is the Born amplitude (unnormalised post-measurement state), not a probability. |CCZ⟩ is SUPPLIED (factory output); distillation correctness is out of scope. But `cczKet` is defined concretely (= cczMat·|+++⟩), NOT axiomatised, and is tied to the repo's 8T→CCZ `cczMat` by `cczKet_eq_cczMat_plus3` below. The other 7 outcomes need a `czMatrix` primitive that the repo lacks (CZ exists only as a circuit `BaseUCom`). The single import `FormalRV.PPM.MagicStateTeleport` transitively provides `StateVec`, `kron_vec` (⊗ᵥ), `basisState`, `kron_vec_apply/high/low` (Core, via `NDSem`) and `cczMat` (`FormalRV.Framework.EightTToCCZ`).
defcczKet
noncomputable def cczKet : StateVec 3
The genuine |CCZ⟩ magic state = CCZ·|+++⟩ = (1/2√2)·∑_d (-1)^[d=7] |d⟩: uniform 1/(2√2) amplitude on every basis state except |111⟩ (index 7), which carries -1/(2√2). The only supplied (factory) object.
defCCZdata
noncomputable def CCZdata (ψ : StateVec 3) : StateVec 3
The CCZ unitary action read entrywise on a 3-qubit data state: phase -1 on the |111⟩ component (index 7).
defcnotChainPerm
def cnotChainPerm (n : Nat) : Nat
The transversal 3-CNOT chain (data qubit k controls ancilla qubit k) as an index permutation: data*8 + anc ↦ data*8 + (anc XOR data). Encoded as a permutation matrix; avoids any 64×64 array literal.
defcnotChain
noncomputable def cnotChain : Matrix (Fin 64) (Fin 64) ℂ
defprojAnc000
noncomputable def projAnc000 : Matrix (Fin 64) (Fin 64) ℂ
Z-measurement projector onto ancilla outcome |000⟩ (low 3 bits = 0).
defplus3
noncomputable def plus3 : StateVec 3
|+++⟩ on 3 qubits = uniform 1/(2√2).
defcczMatData
noncomputable def cczMatData (ψ : StateVec 3) : StateVec 3
The data action spelled as the repo's `cczMat` matrix-vector product.
theoremcnotChainPerm_lt
theorem cnotChainPerm_lt (n : Nat) (h : n < 64) : cnotChainPerm n < 64
theoremcnotChainPerm_invol
theorem cnotChainPerm_invol (n : Nat) (h : n < 64) :
    cnotChainPerm (cnotChainPerm n) = n
theoremcnotChain_mul_apply
theorem cnotChain_mul_apply (v : Matrix (Fin 64) (Fin 1) ℂ) (i : Fin 64) (j : Fin 1) :
    (cnotChain * v) i j = v ⟨cnotChainPerm i.val, cnotChainPerm_lt i.val i.isLt⟩ j
KEY LEMMA: the CNOT chain acts on a column vector by the index permutation, so `(cnotChain * v) i = v (perm i)`. This is what avoids a 64-term brute force (the fin_cases-on-Fin-64 / 4096-goal heartbeat timeout).
theoremcczKet_eq_cczMat_plus3
theorem cczKet_eq_cczMat_plus3 : cczMat * plus3 = cczKet
theoremCCZdata_eq_cczMat_mul
theorem CCZdata_eq_cczMat_mul (ψ : StateVec 3) : CCZdata ψ = cczMat * ψ
theoremccz_teleport_outcome_000
theorem ccz_teleport_outcome_000 (ψ : StateVec 3) :
    projAnc000 * (cnotChain * (ψ ⊗ᵥ cczKet))
      = (1 / (2 * Real.sqrt 2) : ℂ) • (CCZdata ψ ⊗ᵥ (basisState 0 : StateVec 3))
theoremccz_gadget_outcome_000_is_cczMat
theorem ccz_gadget_outcome_000_is_cczMat (ψ : StateVec 3) :
    projAnc000 * (cnotChain * (ψ ⊗ᵥ cczKet))
      = (1 / (2 * Real.sqrt 2) : ℂ) • (cczMatData ψ ⊗ᵥ (basisState 0 : StateVec 3))
theoremccz_gadget_data_is_CCZ
theorem ccz_gadget_data_is_CCZ (ψ : StateVec 3) :
    ∃ c : ℂ, projAnc000 * (cnotChain * (ψ ⊗ᵥ cczKet))
      = c • (cczMatData ψ ⊗ᵥ (basisState 0 : StateVec 3))

FormalRV.PPM.CircuitToPPMFactoryProvision

FormalRV/PPM/CircuitToPPMFactoryProvision.lean
FormalRV.Framework.CircuitToPPMFactoryProvision — closing the gap between the logical arithmetic Gate IR and an *executable* magic-aware PPM program supplied by a T-factory / `RequestMagicState` system call. ## What gap this file closes The E18–E23 stack (`CircuitToPPMSemanticBridge` → `…ObservationBridge` → `…MagicFactory` → `…ToffoliMagic`) proved *soundness* of the magic-aware compiler: IF a run `MagicPPMProgramRel F (compile g) s σ'` exists, THEN `σ'` observes `Gate.applyNat g input`. But three things were missing, and they are exactly the seam between the verified logical circuit and the PPM-with-factory layer: 1. **Executability / totality.** The canonical encoder `magicBasisEncodeBits` produces an *empty* magic pool (`magicPool := []`). `teleportCCXRel` consumes a certified-T token from the head of the pool, so from an empty pool *no run exists* for any circuit containing a Toffoli. The soundness theorems are therefore vacuous on the full arithmetic circuit: nobody proved a successful run **exists**. 2. **Factory system-call provisioning.** The magic pool was an abstract `List MagicToken`. It was never connected to the backend `SysCallKind.RequestMagicState` factory call, nor to the `AtomicFactorySpec` resource model, nor was the *number* of magic requests tied to the circuit's Toffoli count. 3. **Resource ↔ executability link.** Nobody proved that provisioning ≥ (magic demand) certified-T tokens is *sufficient* to run the whole compiled program to completion. This file closes all three at the PPM/logical layer, honestly: `magicCompile_executable` — from a pool of certified-T tokens whose length is ≥ the program's magic demand, a successful run *exists** (with exact pool-consumption bookkeeping `σ'.magicPool = s.magicPool.drop demand`). `compileToMagicPPM_run_observe` / `…_provisioned_run_observe` — executability ∧ the (already-proved) observational soundness, giving **total correctness** at this layer: the program runs AND its output observes `Gate.applyNat g`. `factoryProvision` / `factoryRequestSchedule` — a concrete certified-T token pool and the matching list of `RequestMagicState` system calls; their lengths both equal the circuit's magic demand. `TFactoryContract.ofAtomic` — connects the abstract PPM-layer `TFactoryContract` to the backend `AtomicFactorySpec` (the E21 "future tick can connect them" obligation). `shorMagicDemand_eq_ccxCount` — the magic demand equals the circuit's Toffoli count: one teleported-CCX magic request per `Gate.CCX`. ## Honesty boundary (unchanged from E23) This file does NOT prove (and does not pretend to): the internal Clifford+T circuit realising `teleportCCXRel`; physical T-state distillation / cultivation correctness; QEC / lattice-surgery backend implementation of the factory or of `teleportCCX`; the probabilistic success semantics (we provision the *success* branch and count requests; the per-request failure probability lives in `TFactoryContract.successProbLB_ppm` / `AtomicFactorySpec.success_probability_ppm`, not in the run); QPE / non-Clifford rotations. Everything proved here is structural: the abstract teleportation contract `teleportCCXRel` is taken as the success-branch semantics (E23), and we show the *compiler + factory provisioning* makes a whole verified arithmetic circuit executable and correct modulo that one named contract.
defAllCertifiedT
def AllCertifiedT (F : TFactoryContract) (pool : List MagicToken) : Prop
Every token in `pool` is a certified-T token issued by `F`.
theoremAllCertifiedT_nil
theorem AllCertifiedT_nil (F : TFactoryContract) : AllCertifiedT F []
theoremAllCertifiedT_drop
theorem AllCertifiedT_drop (F : TFactoryContract) :
    ∀ (n : Nat) (pool : List MagicToken),
      AllCertifiedT F pool → AllCertifiedT F (pool.drop n)
Dropping a prefix preserves the all-certified property (every remaining token was already in the pool).
defencodeWithPool
def encodeWithPool (input : Nat → Bool) (pool : List MagicToken) :
    MagicBasisPPMState
theoremencodeWithPool_observes
theorem encodeWithPool_observes (F : TFactoryContract)
    (input : Nat → Bool) (pool : List MagicToken) :
    (magicBasisRefinesApplyNat F).observesBits (encodeWithPool input pool) input
theoremmagicBasisPPMGateRel_ICX_total
theorem magicBasisPPMGateRel_ICX_total :
    ∀ (g : Gate), isICXGate g = true →
      ∀ (s : MagicBasisPPMState),
        ∃ t, magicBasisPPMGateRel g s t
          ∧ t.magicPool = s.magicPool ∧ t.failed = s.failed
theoremcompileMagic_ICX_eq_base_map
theorem compileMagic_ICX_eq_base_map :
    ∀ (g : Gate), isICXGate g = true →
      compileArithmeticGateToMagicPPM g
        = (compileArithmeticGateToPPM g).map MagicPPMCommand.base
For ICX gates the extended compiler equals the base compiler's output wrapped in `.base`. (CCX is the only case that emits the `teleportCCX` primitive.)
theoremmagicCompile_executable_ICX
theorem magicCompile_executable_ICX (F : TFactoryContract) :
    ∀ (g : Gate), isICXGate g = true →
      ∀ (s : MagicBasisPPMState),
        ∃ σ', MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g) s σ'
            ∧ σ'.magicPool = s.magicPool
ICX executability: a run of the extended compiled program exists from any state, leaving the magic pool unchanged (ICX gates request no magic).
theoremmagicCompile_executable
theorem magicCompile_executable (F : TFactoryContract) :
    ∀ (g : Gate) (s : MagicBasisPPMState),
      AllCertifiedT F s.magicPool →
      magicPPMRequestCount (compileArithmeticGateToMagicPPM g) ≤ s.magicPool.length →
      ∃ σ',
        MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g) s σ'
        ∧ σ'.magicPool
            = s.magicPool.drop
                (magicPPMRequestCount (compileArithmeticGateToMagicPPM g))
theoremcompileToMagicPPM_run_observe
theorem compileToMagicPPM_run_observe (F : TFactoryContract)
    (g : Gate) (input : Nat → Bool) (pool : List MagicToken)
    (hcert : AllCertifiedT F pool)
    (hlen : magicPPMRequestCount (compileArithmeticGateToMagicPPM g) ≤ pool.length) :
    ∃ σ',
      MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g)
        (encodeWithPool input pool) σ'
      ∧ (magicBasisRefinesApplyNat F).observesBits σ' (Gate.applyNat g input)
defshorMagicDemand
def shorMagicDemand (g : Gate) : Nat
The magic demand of an arithmetic circuit: the number of certified-T teleportation requests its extended compilation issues (one per `Gate.CCX`).
defcertifiedTToken
def certifiedTToken (F : TFactoryContract) : MagicToken
A single certified-T token issued by factory `F`.
theoremcertifiedTToken_isCertified
theorem certifiedTToken_isCertified (F : TFactoryContract) :
    MagicToken.IsCertifiedTFrom F (certifiedTToken F)
deffactoryProvision
def factoryProvision (F : TFactoryContract) (K : Nat) : List MagicToken
A factory provision of `K` certified-T tokens.
theoremfactoryProvision_length
theorem factoryProvision_length (F : TFactoryContract) (K : Nat) :
    (factoryProvision F K).length = K
theoremfactoryProvision_allCertified
theorem factoryProvision_allCertified (F : TFactoryContract) (K : Nat) :
    AllCertifiedT F (factoryProvision F K)
deffactoryRequestSchedule
def factoryRequestSchedule (factoryZone period_us K : Nat) : List SysCall
The factory **system call** schedule: `K` `RequestMagicState` calls targeting `factoryZone`, pipelined back-to-back at the steady-state period `period_us` (one cultivation output per period).
theoremfactoryRequestSchedule_length
theorem factoryRequestSchedule_length (factoryZone period_us K : Nat) :
    (factoryRequestSchedule factoryZone period_us K).length = K
theoremfactoryRequestSchedule_all_requestMagic
theorem factoryRequestSchedule_all_requestMagic (factoryZone period_us K : Nat) :
    ∀ sc ∈ factoryRequestSchedule factoryZone period_us K,
      sc.kind = SysCallKind.RequestMagicState factoryZone
Every scheduled call is a `RequestMagicState` to the declared factory zone.
deffactoryProvisionLatency
def factoryProvisionLatency (spec : AtomicFactorySpec) (K : Nat) : Nat
Wallclock latency (µs) to provision `K` cultivation outputs, taken from the backend `AtomicFactorySpec` pipeline-latency model.
theoremfactory_schedule_meets_demand
theorem factory_schedule_meets_demand (F : TFactoryContract)
    (factoryZone period_us : Nat) (g : Gate) :
    (factoryRequestSchedule factoryZone period_us (shorMagicDemand g)).length
        = shorMagicDemand g
    ∧ (factoryProvision F (shorMagicDemand g)).length = shorMagicDemand g
*Loop closure**: number of factory `RequestMagicState` system calls = number of certified-T tokens provisioned = the circuit's magic demand. Tokens supplied, requests issued, and demand all agree.
defTFactoryContract.ofAtomic
def TFactoryContract.ofAtomic (spec : AtomicFactorySpec) (fid : Nat) :
    TFactoryContract
Build a PPM-layer `TFactoryContract` from a backend `AtomicFactorySpec`. Output-error ppm is `1 - fidelity`.
theoremTFactoryContract.ofAtomic_wellFormed
theorem TFactoryContract.ofAtomic_wellFormed (spec : AtomicFactorySpec) (fid : Nat)
    (hkind : spec.kind = MagicStateKind.T)
    (hsucc : spec.success_probability_ppm ≤ 1_000_000) :
    (TFactoryContract.ofAtomic spec fid).WellFormed
theoremcompileToMagicPPM_provisioned_run_observe
theorem compileToMagicPPM_provisioned_run_observe (F : TFactoryContract)
    (g : Gate) (input : Nat → Bool) :
    ∃ σ',
      MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g)
        (encodeWithPool input (factoryProvision F (shorMagicDemand g))) σ'
      ∧ (magicBasisRefinesApplyNat F).observesBits σ' (Gate.applyNat g input)
*Provisioned total correctness.** Compile `g` to the extended magic-aware PPM program, provision exactly `shorMagicDemand g` certified-T tokens from `F`, and the program **runs** from the provisioned input state and **observes** `Gate.applyNat g input`. No external Toffoli obligation, no empty-pool vacuity.
theoremcompileToMagicPPM_provisioned_decoder_transfer
theorem compileToMagicPPM_provisioned_decoder_transfer (F : TFactoryContract)
    (g : Gate) (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (hGateCorrect : decode (Gate.applyNat g input) = expected) :
    ∃ σ' output,
      MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g)
        (encodeWithPool input (factoryProvision F (shorMagicDemand g))) σ'
      ∧ (magicBasisRefinesApplyNat F).observesBits σ' output
      ∧ decode output = expected
*Provisioned decoder transfer.** Any `Gate.applyNat`-level decoder postcondition (the shape Shor's arithmetic correctness theorems take) transfers to the provisioned PPM run.
defgateCCXCount
def gateCCXCount : Gate → Nat
  | .I          => 0
  | .X _        => 0
  | .CX _ _     => 0
  | .CCX _ _ _  => 1
  | .seq g₁ g₂  => gateCCXCount g₁ + gateCCXCount g₂
Number of `Gate.CCX` (Toffoli) gates in a circuit.
theoremshorMagicDemand_eq_ccxCount
theorem shorMagicDemand_eq_ccxCount (g : Gate) :
    shorMagicDemand g = gateCCXCount g
The circuit's magic demand equals its Toffoli count: the extended compiler issues exactly one teleported-CCX certified-T request per `Gate.CCX`.

FormalRV.PPM.CircuitToPPMInterface

FormalRV/PPM/CircuitToPPMInterface.lean
(no documented top-level declarations)

FormalRV.PPM.CircuitToPPMInterface.BackendCertificationAndTraceLowering

FormalRV/PPM/CircuitToPPMInterface/BackendCertificationAndTraceLowering.lean
theoremtoySurgeryQECTraceLoweringEvidence
theorem toySurgeryQECTraceLoweringEvidence :
    SurgeryQECTraceLoweringEvidence
      toyQECGadgetSpec
      toySchedulableSurgeryGadget
      toySurgeryVerifiedBackendBlock.schedule

FormalRV.PPM.CircuitToPPMInterface.CircuitFragmentClassifierAndCompiler

FormalRV/PPM/CircuitToPPMInterface/CircuitFragmentClassifierAndCompiler.lean
## §1. Classifier for the supported circuit fragment. The arithmetic fragment is defined PRECISELY by the existing `Gate` IR's constructor set: `I`, `X q`, `CX c t`, `CCX a b t`, `seq g₁ g₂`. There is no `Rz`, `H`, `T`, `phase`, or opaque oracle constructor in `Gate`, so the arithmetic-fragment classifier on `Gate` is constructively total: every `Gate` is in the arithmetic fragment by construction. For circuits expressed in the broader `BaseUCom` IR (which has `BaseUnitary.R θ φ λ` as a 1-qubit primitive), real-angle comparison is undecidable, so we tag those circuits as `unsupportedOpaque` or `qpePhaseRotation` by structure — they must be lowered to the `Gate` IR separately before entering the PPM path.
inductiveCircuitFragmentKind
inductive CircuitFragmentKind
Classification of a circuit fragment for PPM lowering. `arithmetic` — the existing `Gate` arithmetic fragment (I, X, CNOT, Toffoli, sequential composition). These enter the PPM lowering directly. `cliffordT` — generic Clifford+T circuits already decomposed into H/S/T/CNOT. Reserved for a future tick that handles general Clifford+T to PPM lowering. `qpePhaseRotation` — controlled phase rotations (`controlled_Rz`, `controlled_R`) used in QPE/QFT. REJECTED unless decomposed to Clifford+T or to the arithmetic Gate IR first. `unsupportedOpaque` — opaque/oracle gates with no structural decomposition supplied. REJECTED.
defclassifyGateForPPMLowering
def classifyGateForPPMLowering : Gate → CircuitFragmentKind
  | .I        => .arithmetic
  | .X _      => .arithmetic
  | .CX _ _   => .arithmetic
  | .CCX _ _ _ => .arithmetic
  | .seq _ _  => .arithmetic
Every `Gate` is in the arithmetic fragment by construction: the IR's constructors are exactly `I | X | CX | CCX | seq`.
defisArithmeticGate
def isArithmeticGate (g : Gate) : Bool
Bool form: `true` iff the gate is in the supported arithmetic fragment. Always `true` for the existing `Gate` IR.
theoremisArithmeticGate_eq_true
theorem isArithmeticGate_eq_true (g : Gate) : isArithmeticGate g = true
defclassifyBaseUnitary1ForPPMLowering
def classifyBaseUnitary1ForPPMLowering : BaseUnitary 1 → CircuitFragmentKind
  | .R _ _ _ => .qpePhaseRotation   -- conservative: rotated unless decomposed
defclassifyBaseUnitary2ForPPMLowering
def classifyBaseUnitary2ForPPMLowering : BaseUnitary 2 → CircuitFragmentKind
  | .CNOT => .cliffordT
defclassifyBaseUComForPPMLowering
def classifyBaseUComForPPMLowering {dim : Nat} : BaseUCom dim → CircuitFragmentKind
  | .seq c₁ c₂ =>
      match classifyBaseUComForPPMLowering c₁, classifyBaseUComForPPMLowering c₂ with
      | .unsupportedOpaque, _ | _, .unsupportedOpaque => .unsupportedOpaque
      | .qpePhaseRotation, _ | _, .qpePhaseRotation   => .qpePhaseRotation
      | _, _                                          => .cliffordT
  | .app1 u _       => classifyBaseUnitary1ForPPMLowering u
  | .app2 u _ _     => classifyBaseUnitary2ForPPMLowering u
  | .app3 _ _ _ _   => .unsupportedOpaque
Structural classifier for `BaseUCom dim`. Worst-case wins (qpePhaseRotation dominates cliffordT dominates arithmetic).
inductivePPMCommand
inductive PPMCommand
abbrevPPMProgram
abbrev PPMProgram
A PPM program is a sequence of PPM commands.
defcompileArithmeticGateToPPM
def compileArithmeticGateToPPM : Gate → PPMProgram
  | .I         => []
  | .X q       => [.applyFrameUpdate [q]]
  | .CX c t    =>
      [ .measurePauliKind PauliKind.Z [c, t]
      , .applyFrameUpdate [t] ]
  | .CCX a b t =>
      [ .useMagicT t
      , .measurePauliKind PauliKind.Z [a, b, t]
      , .applyFrameUpdate [t] ]
  | .seq g₁ g₂ =>
      compileArithmeticGateToPPM g₁ ++ compileArithmeticGateToPPM g₂
theoremcompileArithmeticGateToPPM_I
theorem compileArithmeticGateToPPM_I :
    compileArithmeticGateToPPM .I = []
theoremcompileArithmeticGateToPPM_seq
theorem compileArithmeticGateToPPM_seq (g₁ g₂ : Gate) :
    compileArithmeticGateToPPM (.seq g₁ g₂)
      = compileArithmeticGateToPPM g₁
          ++ compileArithmeticGateToPPM g₂
theoremisArithmeticGate_of_Gate
theorem isArithmeticGate_of_Gate (g : Gate) : isArithmeticGate g = true
Acceptance theorem: every `Gate` is in the arithmetic fragment, hence accepted by the compiler.
structureGateToPPMSemanticsModel
structure GateToPPMSemanticsModel
Abstract semantic model that pairs the arithmetic Gate semantics with the PPM command semantics on a shared state type. Instantiating `State`, `gateRel`, and `ppmCommandRel` with concrete definitions (e.g., `StabilizerState` + Gottesman updates) recovers a real semantic model. None of this file's theorems require a specific instantiation.
inductivePPMProgramRel
inductive PPMProgramRel (sem : GateToPPMSemanticsModel) :
    PPMProgram → sem.State → sem.State → Prop
  | nil  (s : sem.State) : PPMProgramRel sem [] s s
  | cons {cmd : PPMCommand} {rest : PPMProgram}
         {s t u : sem.State}
         (h1 : sem.ppmCommandRel cmd s t)
         (h2 : PPMProgramRel sem rest t u) :
         PPMProgramRel sem (cmd :: rest) s u
Inductive relational semantics of a `PPMProgram`: the transitive closure of `ppmCommandRel` along the command list.
defImplementsGateAsPPM
def ImplementsGateAsPPM
    (sem : GateToPPMSemanticsModel)
    (g : Gate) (ppm : PPMProgram) : Prop
The PPM program faithfully implements the gate iff every gate transition `s → t` is realised by a PPM-program transition `s → t`.
theoremPPMProgramRel_append
theorem PPMProgramRel_append
    (sem : GateToPPMSemanticsModel) (p₁ p₂ : PPMProgram)
    (s u : sem.State) :
    PPMProgramRel sem (p₁ ++ p₂) s u ↔
      ∃ t, PPMProgramRel sem p₁ s t ∧ PPMProgramRel sem p₂ t u
Append-decomposition for the inductive PPM semantics: the program `p₁ ++ p₂` realises `s ⇒ u` iff there is an intermediate state `t` such that `p₁` realises `s ⇒ t` and `p₂` realises `t ⇒ u`.
structureArithmeticPrimitivePPMObligations
structure ArithmeticPrimitivePPMObligations
    (sem : GateToPPMSemanticsModel)
theoremcompileArithmeticGateToPPM_sound_from_primitives
theorem compileArithmeticGateToPPM_sound_from_primitives
    (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem) :
    ∀ g, ImplementsGateAsPPM sem g (compileArithmeticGateToPPM g)
structureVerifiedPPMMacro
structure VerifiedPPMMacro (sem : GateToPPMSemanticsModel)
defmacroForX
def macroForX (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem)
    (q : LogicalQubitId) (rounds distance : Nat) :
    VerifiedPPMMacro sem
Macro record for an `X` gate. Discharges its semantic obligation from the user-supplied `X_ok` primitive.
defmacroForCNOT
def macroForCNOT (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem)
    (c t : LogicalQubitId) (rounds distance : Nat) :
    VerifiedPPMMacro sem
Macro record for a CNOT gate.
defmacroForToffoli
def macroForToffoli (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem)
    (a b t : LogicalQubitId) (rounds distance : Nat) :
    VerifiedPPMMacro sem
Macro record for a Toffoli gate.
structureVerifiedArithmeticPPMBlock
structure VerifiedArithmeticPPMBlock
    (sem : GateToPPMSemanticsModel)
defVerifiedArithmeticPPMBlock.ofGate
def VerifiedArithmeticPPMBlock.ofGate
    (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem)
    (g : Gate) :
    VerifiedArithmeticPPMBlock sem
Canonical constructor: from any `Gate` and a supplied primitive-obligations witness, build a `VerifiedArithmeticPPMBlock` whose `semantic_ok` field is the induction theorem applied to the obligations. The `True` stand-in from the previous version is GONE. A user that wants to build a `VerifiedArithmeticPPMBlock` must supply a real semantic model plus primitive proofs; the interface itself does not fabricate semantic correctness.
defpauliOfPauliKind
def pauliOfPauliKind : PauliKind → PauliSem.Pauli
  | .I => PauliSem.Pauli.I
  | .X => PauliSem.Pauli.X
  | .Y => PauliSem.Pauli.Y
  | .Z => PauliSem.Pauli.Z
Conversion from the `Architecture.PauliKind` (I/X/Y/Z used in `PPMSpec`, `PauliMeasurementClaim`) to the `PauliSem.Pauli` (used in `PauliString.ops`).
defpauliOpListOfKindOnQubits
def pauliOpListOfKindOnQubits
    (n : Nat) (pk : PauliKind) (qs : List LogicalQubitId) :
    List PauliSem.Pauli
Build the n-qubit Pauli operator list with `pauliOfPauliKind pk` on every index in `qs` and `Pauli.I` on every other index, by iterating from `0` to `n-1`.
defpauliStringOfKindOnQubits
def pauliStringOfKindOnQubits
    (n : Nat) (pk : PauliKind) (qs : List LogicalQubitId) :
    Option PauliSem.PauliString
The full PauliString (length n, phase +) used to interpret `PPMCommand.measurePauliKind pk qs` against the n-qubit stabilizer state. Returns `none` if any qubit in `qs` is out of bounds `< n`; otherwise `some` of the n-length Pauli string.
theorempauliStringOfKindOnQubits_length
theorem pauliStringOfKindOnQubits_length
    (n : Nat) (pk : PauliKind) (qs : List LogicalQubitId)
    (P : PauliSem.PauliString)
    (h : pauliStringOfKindOnQubits n pk qs = some P) :
    P.ops.length = n
defstabilizerPPMCommandRel
def stabilizerPPMCommandRel (n : Nat) :
    PPMCommand → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop
  | .measurePauliKind pk qs, s, t =>
      ∃ P : PauliSem.PauliString,
        pauliStringOfKindOnQubits n pk qs = some P
        ∧ (t = PPMOp.apply_PPM_pos s P ∨ t = PPMOp.apply_PPM_neg s P)
  | .applyFrameUpdate _,    s, t => t = s
  | .useMagicT _,           s, t => t = s
Concrete PPM command relation on `StabilizerState`. `measurePauliKind`: nondeterministic stabilizer Pauli measurement, taking either Gottesman update branch (+1 outcome ↔ `apply_PPM_pos`, −1 outcome ↔ `apply_PPM_neg`). The relation includes the existential over the decoded PauliString. `applyFrameUpdate`: identity transition (see §13 header). Frame bookkeeping is deferred. `useMagicT`: identity transition (see §13 header). Non-Clifford magic-T injection is deferred.
defstabilizerPPMSemanticsModel
def stabilizerPPMSemanticsModel
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop) :
    GateToPPMSemanticsModel
Concrete semantic model: `State = StabilizerState`, `ppmCommandRel = stabilizerPPMCommandRel n`, and `gateRel` is supplied by the user (no canonical `Gate → StabilizerState → StabilizerState → Prop` exists in the repo yet).
defmkStabilizerPrimitiveObligations
def mkStabilizerPrimitiveObligations
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop)
    (hI  : ∀ s t, gateRel Gate.I s t → s = t)
    (hX  : ∀ q,
        ImplementsGateAsPPM (stabilizerPPMSemanticsModel n gateRel)
          (Gate.X q) (compileArithmeticGateToPPM (Gate.X q)))
    (hCX : ∀ c t,
        ImplementsGateAsPPM (stabilizerPPMSemanticsModel n gateRel)
          (Gate.CX c t) (compileArithmeticGateToPPM (Gate.CX c t)))
    (hCCX : ∀ a b t,
        ImplementsGateAsPPM (stabilizerPPMSemanticsModel n gateRel)
theoremPPMProgramRel_measure_single_step_pos
theorem PPMProgramRel_measure_single_step_pos
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop)
    (pk : PauliKind) (qs : List LogicalQubitId) (s : PPMOp.StabilizerState)
    (P : PauliSem.PauliString)
    (h : pauliStringOfKindOnQubits n pk qs = some P) :
    PPMProgramRel (stabilizerPPMSemanticsModel n gateRel)
      [PPMCommand.measurePauliKind pk qs]
      s
      (PPMOp.apply_PPM_pos s P)
`[measurePauliKind pk qs]` applied to `s` reaches `apply_PPM_pos s P` when the decoded PauliString is `P`.
theoremPPMProgramRel_measure_single_step_neg
theorem PPMProgramRel_measure_single_step_neg
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop)
    (pk : PauliKind) (qs : List LogicalQubitId) (s : PPMOp.StabilizerState)
    (P : PauliSem.PauliString)
    (h : pauliStringOfKindOnQubits n pk qs = some P) :
    PPMProgramRel (stabilizerPPMSemanticsModel n gateRel)
      [PPMCommand.measurePauliKind pk qs]
      s
      (PPMOp.apply_PPM_neg s P)
Negative-outcome companion of `PPMProgramRel_measure_single_step_pos`.
theoremPPMProgramRel_applyFrameUpdate_single_step
theorem PPMProgramRel_applyFrameUpdate_single_step
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop)
    (qs : List LogicalQubitId) (s : PPMOp.StabilizerState) :
    PPMProgramRel (stabilizerPPMSemanticsModel n gateRel)
      [PPMCommand.applyFrameUpdate qs] s s
`[applyFrameUpdate qs]` is an identity step on `StabilizerState`.
theoremPPMProgramRel_useMagicT_single_step
theorem PPMProgramRel_useMagicT_single_step
    (n : Nat)
    (gateRel : Gate → PPMOp.StabilizerState → PPMOp.StabilizerState → Prop)
    (q : LogicalQubitId) (s : PPMOp.StabilizerState) :
    PPMProgramRel (stabilizerPPMSemanticsModel n gateRel)
      [PPMCommand.useMagicT q] s s
`[useMagicT q]` is an identity step on `StabilizerState`.
structureLogicalPauliFrame
structure LogicalPauliFrame
defLogicalPauliFrame.empty
def LogicalPauliFrame.empty : LogicalPauliFrame
The empty (no-correction) frame.
defLogicalPauliFrame.toggleX
def LogicalPauliFrame.toggleX (frame : LogicalPauliFrame)
    (q : LogicalQubitId) : LogicalPauliFrame
Toggle the X-frame entry for one qubit: if `q` is in `xFrame`, remove it (the pending X correction has been cancelled out by another X); otherwise prepend `q`.
defLogicalPauliFrame.toggleZ
def LogicalPauliFrame.toggleZ (frame : LogicalPauliFrame)
    (q : LogicalQubitId) : LogicalPauliFrame
Toggle the Z-frame entry for one qubit.
defLogicalPauliFrame.toggleXList
def LogicalPauliFrame.toggleXList (frame : LogicalPauliFrame)
    (qs : List LogicalQubitId) : LogicalPauliFrame
Toggle the X-frame on every qubit in a list (left fold).
defLogicalPauliFrame.toggleZList
def LogicalPauliFrame.toggleZList (frame : LogicalPauliFrame)
    (qs : List LogicalQubitId) : LogicalPauliFrame
Toggle the Z-frame on every qubit in a list.
structureLogicalPPMState
structure LogicalPPMState
defLogicalPPMState.empty
def LogicalPPMState.empty (n : Nat) : LogicalPPMState
Canonical empty enriched state on `n` qubits. Stabilizer starts as the n-qubit identity stabilizer (no constraints), frame is empty, no magic used.
deflogicalPPMCommandRel
def logicalPPMCommandRel (n : Nat) :
    PPMCommand → LogicalPPMState → LogicalPPMState → Prop
  | .measurePauliKind pk qs, s, t =>
      ∃ P : PauliSem.PauliString,
        pauliStringOfKindOnQubits n pk qs = some P
        ∧ ( (t.stabilizer = PPMOp.apply_PPM_pos s.stabilizer P ∨
             t.stabilizer = PPMOp.apply_PPM_neg s.stabilizer P)
            ∧ t.frame = s.frame
            ∧ t.magicUsed = s.magicUsed )
  | .applyFrameUpdate qs,   s, t =>
      t.stabilizer = s.stabilizer
      ∧ t.frame = s.frame.toggleXList qs
Concrete PPM command relation on `LogicalPPMState`. `measurePauliKind`: stabilizer is updated by either Gottesman branch; frame and magicUsed are PRESERVED. `applyFrameUpdate qs`: stabilizer is preserved; X-frame is toggled on each qubit in `qs`; magicUsed preserved. `useMagicT _`: stabilizer and frame preserved; magicUsed is INCREMENTED by 1. This is resource accounting; it does NOT implement the non-Clifford action of a T-state injection.
deflogicalPPMSemanticsModel
def logicalPPMSemanticsModel
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop) :
    GateToPPMSemanticsModel
theoremPPMProgramRel_logical_measure_single_step_pos
theorem PPMProgramRel_logical_measure_single_step_pos
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop)
    (pk : PauliKind) (qs : List LogicalQubitId)
    (s : LogicalPPMState) (P : PauliSem.PauliString)
    (h : pauliStringOfKindOnQubits n pk qs = some P) :
    PPMProgramRel (logicalPPMSemanticsModel n gateRel)
      [PPMCommand.measurePauliKind pk qs]
      s
      { stabilizer
`[measurePauliKind pk qs]` reaches a state with stabilizer `apply_PPM_pos s.stabilizer P` (+1 outcome), preserving frame and magicUsed.
theoremPPMProgramRel_logical_measure_single_step_neg
theorem PPMProgramRel_logical_measure_single_step_neg
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop)
    (pk : PauliKind) (qs : List LogicalQubitId)
    (s : LogicalPPMState) (P : PauliSem.PauliString)
    (h : pauliStringOfKindOnQubits n pk qs = some P) :
    PPMProgramRel (logicalPPMSemanticsModel n gateRel)
      [PPMCommand.measurePauliKind pk qs]
      s
      { stabilizer
Negative-outcome companion of `PPMProgramRel_logical_measure_single_step_pos`.
theoremPPMProgramRel_logical_applyFrameUpdate_single_step
theorem PPMProgramRel_logical_applyFrameUpdate_single_step
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop)
    (qs : List LogicalQubitId) (s : LogicalPPMState) :
    PPMProgramRel (logicalPPMSemanticsModel n gateRel)
      [PPMCommand.applyFrameUpdate qs]
      s
      { stabilizer
`[applyFrameUpdate qs]` reaches a state with the X-frame toggled on each `q ∈ qs`, preserving stabilizer and magicUsed.
theoremPPMProgramRel_logical_useMagicT_single_step
theorem PPMProgramRel_logical_useMagicT_single_step
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop)
    (q : LogicalQubitId) (s : LogicalPPMState) :
    PPMProgramRel (logicalPPMSemanticsModel n gateRel)
      [PPMCommand.useMagicT q]
      s
      { stabilizer
`[useMagicT q]` reaches a state with `magicUsed` incremented and stabilizer/frame preserved.
defmkLogicalPPMPrimitiveObligations
def mkLogicalPPMPrimitiveObligations
    (n : Nat)
    (gateRel : Gate → LogicalPPMState → LogicalPPMState → Prop)
    (hI  : ∀ s t, gateRel Gate.I s t → s = t)
    (hX  : ∀ q,
        ImplementsGateAsPPM (logicalPPMSemanticsModel n gateRel)
          (Gate.X q) (compileArithmeticGateToPPM (Gate.X q)))
    (hCX : ∀ c t,
        ImplementsGateAsPPM (logicalPPMSemanticsModel n gateRel)
          (Gate.CX c t) (compileArithmeticGateToPPM (Gate.CX c t)))
    (hCCX : ∀ a b t,
        ImplementsGateAsPPM (logicalPPMSemanticsModel n gateRel)
defframeLevelGateRel
def frameLevelGateRel : Gate → LogicalPPMState → LogicalPPMState → Prop
  | .I,        s, t => t = s
  | .X q,      s, t =>
      t.stabilizer = s.stabilizer
      ∧ t.frame = s.frame.toggleX q
      ∧ t.magicUsed = s.magicUsed
  | .CX _ _,   _, _ => False
  | .CCX _ _ _, _, _ => False
  | .seq g₁ g₂, s, u =>
      ∃ mid, frameLevelGateRel g₁ s mid ∧ frameLevelGateRel g₂ mid u
Frame-level gate relation. Captures the macro-level transition that the §4 compiler's output programs would produce on `LogicalPPMState`, for the I and X cases. CX and CCX are `False` (not supported by this lightweight deferred-frame model).
defframeLevelPPMSemanticsModel
def frameLevelPPMSemanticsModel (n : Nat) : GateToPPMSemanticsModel
Semantics model that wires `frameLevelGateRel` into the enriched §14 model.
theoremframeLevelGateRel_I
theorem frameLevelGateRel_I (s t : LogicalPPMState) :
    frameLevelGateRel Gate.I s t ↔ t = s
theoremframeLevelGateRel_X
theorem frameLevelGateRel_X (q : LogicalQubitId) (s t : LogicalPPMState) :
    frameLevelGateRel (Gate.X q) s t ↔
      ( t.stabilizer = s.stabilizer
        ∧ t.frame = s.frame.toggleX q
        ∧ t.magicUsed = s.magicUsed )
theoremframeLevelGateRel_seq_decomp
theorem frameLevelGateRel_seq_decomp (g₁ g₂ : Gate) (s u : LogicalPPMState) :
    frameLevelGateRel (Gate.seq g₁ g₂) s u ↔
      ∃ mid, frameLevelGateRel g₁ s mid ∧ frameLevelGateRel g₂ mid u
theoremframeLevel_I_is_id
theorem frameLevel_I_is_id (s t : LogicalPPMState)
    (h : frameLevelGateRel Gate.I s t) : s = t
theoremframeLevel_X_ok
theorem frameLevel_X_ok (n : Nat) (q : LogicalQubitId) :
    ImplementsGateAsPPM (frameLevelPPMSemanticsModel n) (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
structureArithmeticIXPrimitivePPMObligations
structure ArithmeticIXPrimitivePPMObligations
    (sem : GateToPPMSemanticsModel)
defframeLevelIXObligations
def frameLevelIXObligations (n : Nat) :
    ArithmeticIXPrimitivePPMObligations (frameLevelPPMSemanticsModel n)
Canonical IX bundle for the frame-level model.
defcxMacroGateRel
def cxMacroGateRel (n : Nat) :
    Gate → LogicalPPMState → LogicalPPMState → Prop
  | .I,        s, t => t = s
  | .X q,      s, t =>
      t.stabilizer = s.stabilizer
      ∧ t.frame = s.frame.toggleX q
      ∧ t.magicUsed = s.magicUsed
  | .CX c tgt, s, u =>
      ∃ (P : PauliSem.PauliString) (mid : LogicalPPMState),
        pauliStringOfKindOnQubits n PauliKind.Z [c, tgt] = some P
        ∧ ( mid.stabilizer = PPMOp.apply_PPM_pos s.stabilizer P
            ∨ mid.stabilizer = PPMOp.apply_PPM_neg s.stabilizer P )
CX-aware macro-specified gate relation. The `n` argument fixes the qubit register size for `PauliString` decoding.
defcxMacroPPMSemanticsModel
def cxMacroPPMSemanticsModel (n : Nat) : GateToPPMSemanticsModel
Semantics model wiring `cxMacroGateRel n` into the enriched §14 model.
theoremcxMacroGateRel_I
theorem cxMacroGateRel_I (n : Nat) (s t : LogicalPPMState) :
    cxMacroGateRel n Gate.I s t ↔ t = s
theoremcxMacroGateRel_X
theorem cxMacroGateRel_X (n : Nat) (q : LogicalQubitId) (s t : LogicalPPMState) :
    cxMacroGateRel n (Gate.X q) s t ↔
      ( t.stabilizer = s.stabilizer
        ∧ t.frame = s.frame.toggleX q
        ∧ t.magicUsed = s.magicUsed )
theoremcxMacroGateRel_seq_decomp
theorem cxMacroGateRel_seq_decomp (n : Nat) (g₁ g₂ : Gate)
    (s u : LogicalPPMState) :
    cxMacroGateRel n (Gate.seq g₁ g₂) s u ↔
      ∃ mid, cxMacroGateRel n g₁ s mid ∧ cxMacroGateRel n g₂ mid u
theoremcxMacro_I_is_id
theorem cxMacro_I_is_id (n : Nat) (s t : LogicalPPMState)
    (h : cxMacroGateRel n Gate.I s t) : s = t
theoremcxMacro_X_ok
theorem cxMacro_X_ok (n : Nat) (q : LogicalQubitId) :
    ImplementsGateAsPPM (cxMacroPPMSemanticsModel n) (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
theoremcxMacro_CX_ok
theorem cxMacro_CX_ok (n : Nat) (c tgt : LogicalQubitId) :
    ImplementsGateAsPPM (cxMacroPPMSemanticsModel n) (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
structureArithmeticICXPrimitivePPMObligations
structure ArithmeticICXPrimitivePPMObligations
    (sem : GateToPPMSemanticsModel)
defcxMacroICXObligations
def cxMacroICXObligations (n : Nat) :
    ArithmeticICXPrimitivePPMObligations (cxMacroPPMSemanticsModel n)
Canonical ICX bundle for the CX-aware model.
defisICXGate
def isICXGate : Gate → Bool
  | .I         => true
  | .X _       => true
  | .CX _ _    => true
  | .CCX _ _ _ => false
  | .seq g₁ g₂ => isICXGate g₁ && isICXGate g₂
theoremcompileICXGateToPPM_sound_from_cxMacro
theorem compileICXGateToPPM_sound_from_cxMacro (n : Nat) :
    ∀ g, isICXGate g = true →
      ImplementsGateAsPPM (cxMacroPPMSemanticsModel n) g
        (compileArithmeticGateToPPM g)
structureMagicAwarePPMState
structure MagicAwarePPMState

FormalRV.PPM.CircuitToPPMInterface.CircuitToPPMInterfaceModuleEnd

FormalRV/PPM/CircuitToPPMInterface/CircuitToPPMInterfaceModuleEnd.lean
(no documented top-level declarations)

FormalRV.PPM.CircuitToPPMInterface.CircuitToPPMInterfaceOverview

FormalRV/PPM/CircuitToPPMInterface/CircuitToPPMInterfaceOverview.lean
FormalRV.Framework.CircuitToPPMInterface — the first high-level-circuit → PPM lowering interface for the ARITHMETIC fragment of FT-Shor. ## Scope This file defines a structural lowering from the existing arithmetic-only Gate IR (`FormalRV.Framework.Gate`, constructors `I | X | CX | CCX | seq`) into a logical-layer PPM program (`PPMCommand` / `PPMProgram`). It targets the arithmetic subcircuits of Shor (modular-exponentiation, modular-multiplication, modular-addition, Cuccaro adders, Gidney 2018 adders, etc.) — NOT the QPE phase-rotation fragment, which generally requires either exact-Clifford+T decomposition or approximate synthesis before it can enter this PPM path. ## Layering (recap) Logical Shor / arithmetic correctness ↓ (Clifford+T / Toffoli-CNOT-X arithmetic fragment, THIS FILE) PPM / lattice-surgery logical-measurement layer ↓ QEC gadget implementation ↓ Backend compressed SysCall schedule ↓ System resource/invariant certificate The arithmetic fragment lives ABOVE the PPM layer. The PPM layer lives ABOVE the SysCall/System layer. Do not collapse PPM into physical SysCall schedules. ## What is and is NOT proved in this tick Proved structurally: Empty `Gate.I` compiles to `[]`. `Gate.seq g₁ g₂` compiles to the append of the compiled halves. NOT proved: Semantic equivalence between the source `Gate` and the compiled `PPMProgram`. The user must supply a separate semantic proof; the interface records the obligation as a `Prop` slot. Existing definitions REUSED: `FormalRV.Framework.Gate` — the arithmetic Gate IR. `FormalRV.Framework.Architecture.PauliKind` — I/X/Y/Z. `FormalRV.Framework.LayeredPPMQECInterface.PPMSpec`, `QECGadgetSpec`, `LogicalQubitId`, `PauliKind` re-export. Existing definitions deferred: `BaseUCom dim` (`QuantumGate.lean`) — QPE-capable IR with real-angle R primitives. Real-angle equality is not decidable, so the BaseUCom-side classifier here only tags structural kinds (CNOT vs R), not specific Clifford+T rewrites. Real lowering of BaseUCom (decompose to Gate) is a future tick. `PPMOperational.StabilizerState` and Gottesman PPM updates — these formalise PPM operational semantics; they will be consumed by the future `semantic_obligation` refinement.
(no documented top-level declarations)

FormalRV.PPM.CircuitToPPMInterface.EnrichedPPMStateAndIntegration

FormalRV/PPM/CircuitToPPMInterface/EnrichedPPMStateAndIntegration.lean
defMagicAwarePPMState.empty
def MagicAwarePPMState.empty (n : Nat) : MagicAwarePPMState
Canonical empty state on `n` qubits. Underlying `LogicalPPMState.empty n` plus empty magic log.
defmagicAwarePPMCommandRel
def magicAwarePPMCommandRel (n : Nat) :
    PPMCommand → MagicAwarePPMState → MagicAwarePPMState → Prop
  | .measurePauliKind pk qs, s, t =>
      logicalPPMCommandRel n (PPMCommand.measurePauliKind pk qs)
        s.logicalState t.logicalState
      ∧ t.magicLog = s.magicLog
  | .applyFrameUpdate qs,    s, t =>
      logicalPPMCommandRel n (PPMCommand.applyFrameUpdate qs)
        s.logicalState t.logicalState
      ∧ t.magicLog = s.magicLog
  | .useMagicT q,            s, t =>
      logicalPPMCommandRel n (PPMCommand.useMagicT q)
defmagicAwarePPMSemanticsModel
def magicAwarePPMSemanticsModel
    (n : Nat)
    (gateRel : Gate → MagicAwarePPMState → MagicAwarePPMState → Prop) :
    GateToPPMSemanticsModel
structureMagicInjectionObligations
structure MagicInjectionObligations
    (sem : GateToPPMSemanticsModel)
defmkArithmeticPrimitiveObligationsWithMagic
def mkArithmeticPrimitiveObligationsWithMagic
    (sem : GateToPPMSemanticsModel)
    (icx : ArithmeticICXPrimitivePPMObligations sem)
    (mag : MagicInjectionObligations sem)
    (hseq : ∀ g₁ g₂ s u,
      sem.gateRel (Gate.seq g₁ g₂) s u ↔
        ∃ t, sem.gateRel g₁ s t ∧ sem.gateRel g₂ t u) :
    ArithmeticPrimitivePPMObligations sem
theoremcompileArithmeticGateToPPM_sound_from_magic_interface
theorem compileArithmeticGateToPPM_sound_from_magic_interface
    (sem : GateToPPMSemanticsModel)
    (icx : ArithmeticICXPrimitivePPMObligations sem)
    (mag : MagicInjectionObligations sem)
    (hseq : ∀ g₁ g₂ s u,
      sem.gateRel (Gate.seq g₁ g₂) s u ↔
        ∃ t, sem.gateRel g₁ s t ∧ sem.gateRel g₂ t u) :
    ∀ g, ImplementsGateAsPPM sem g (compileArithmeticGateToPPM g)
structureVerifiedArithmeticToPPMBlock
structure VerifiedArithmeticToPPMBlock
    (sem : GateToPPMSemanticsModel)
defVerifiedArithmeticToPPMBlock.ofPrimitiveObligations
def VerifiedArithmeticToPPMBlock.ofPrimitiveObligations
    (sem : GateToPPMSemanticsModel)
    (obs : ArithmeticPrimitivePPMObligations sem)
    (g : Gate) :
    VerifiedArithmeticToPPMBlock sem
Constructor (A): from a full `ArithmeticPrimitivePPMObligations` bundle. Uses the §9 induction theorem to discharge `semantic_ok`.
defVerifiedArithmeticToPPMBlock.ofICX
def VerifiedArithmeticToPPMBlock.ofICX
    (n : Nat) (g : Gate) (hg : isICXGate g = true) :
    VerifiedArithmeticToPPMBlock (cxMacroPPMSemanticsModel n)
Constructor (B): from the §16 ICX-fragment soundness. Restricted to circuits with `isICXGate g = true`, i.e., `Gate.CCX` is rejected. Discharges `semantic_ok` against `cxMacroPPMSemanticsModel n`.
defVerifiedArithmeticToPPMBlock.ofMagicInterface
def VerifiedArithmeticToPPMBlock.ofMagicInterface
    (sem : GateToPPMSemanticsModel)
    (icx : ArithmeticICXPrimitivePPMObligations sem)
    (mag : MagicInjectionObligations sem)
    (hseq : ∀ g₁ g₂ s u,
      sem.gateRel (Gate.seq g₁ g₂) s u ↔
        ∃ t, sem.gateRel g₁ s t ∧ sem.gateRel g₂ t u)
    (g : Gate) :
    VerifiedArithmeticToPPMBlock sem
Constructor (C): from an ICX bundle, a magic-injection obligation bundle (carrying the deferred `CCX_ok`), and a `seq_decomp` hypothesis. Discharges `semantic_ok` against the user-supplied `sem` via `compileArithmeticGateToPPM_sound_from_magic_interface`.
structureArithmeticPPMSpec
structure ArithmeticPPMSpec
Thin pairing of `Gate` and its compiled `PPMProgram`. `PPMSpec` is reserved for measurement-spec objects; `ArithmeticPPMSpec` is the description-side pairing.
structureVerifiedArithmeticPPMProgramBlock
structure VerifiedArithmeticPPMProgramBlock
    (sem : GateToPPMSemanticsModel)
A verified arithmetic-to-PPM block enriched with lists of `PPMSpec` and `QECGadgetSpec` summaries. Still ABOVE the backend.
structureVerifiedArithmeticPPMToSystemBlock
structure VerifiedArithmeticPPMToSystemBlock
    (models : SystemModels) (sem : GateToPPMSemanticsModel)
theoremVerifiedArithmeticPPMToSystemBlock.system_invariants_ok
theorem VerifiedArithmeticPPMToSystemBlock.system_invariants_ok
    (models : SystemModels) (sem : GateToPPMSemanticsModel)
    (b : VerifiedArithmeticPPMToSystemBlock models sem) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        models.arch
        models.opCap
        models.slotCap
        models.ancillaModel
        b.backend.schedule.expand
        models.t_react_us
        models.window_us
        models.max_per_window = true
structurePPMToBackendLoweringModel
structure PPMToBackendLoweringModel
    (models : SystemModels) (sem : GateToPPMSemanticsModel)
Abstract lowering model. The user supplies three relations describing what it MEANS for: a `PPMProgram` to implement a list of `PPMSpec`s, a list of `QECGadgetSpec`s to be realised by a `CompressedSchedule`, a `PPMProgram` and a `CompressedSchedule` to align in resource accounting. No relation is `True` or axiomatised. A concrete instantiation must supply actual relations; the obligation structure below requires real proofs.
structurePPMProgramToBackendLoweringObligation
structure PPMProgramToBackendLoweringObligation
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
structureVerifiedArithmeticPPMToSystemBlockV2
structure VerifiedArithmeticPPMToSystemBlockV2
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
theoremVerifiedArithmeticPPMToSystemBlockV2.system_invariants_ok
theorem VerifiedArithmeticPPMToSystemBlockV2.system_invariants_ok
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
    (b : VerifiedArithmeticPPMToSystemBlockV2 models sem lowering) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        models.arch
        models.opCap
        models.slotCap
        models.ancillaModel
        b.backend.schedule.expand
        models.t_react_us
theoremVerifiedArithmeticPPMToSystemBlockV2.ppm_semantic
theorem VerifiedArithmeticPPMToSystemBlockV2.ppm_semantic
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
    (b : VerifiedArithmeticPPMToSystemBlockV2 models sem lowering) :
    lowering.ppmProgramImplementsSpecs
      b.arithmeticPPM.arithmetic.ppmProgram
      b.arithmeticPPM.ppmSpecs
theoremVerifiedArithmeticPPMToSystemBlockV2.qec_backend
theorem VerifiedArithmeticPPMToSystemBlockV2.qec_backend
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
    (b : VerifiedArithmeticPPMToSystemBlockV2 models sem lowering) :
    lowering.qecSpecsLowerToSchedule
      b.arithmeticPPM.qecSpecs
      b.backend.schedule
theoremVerifiedArithmeticPPMToSystemBlockV2.resource_alignment
theorem VerifiedArithmeticPPMToSystemBlockV2.resource_alignment
    (models : SystemModels)
    (sem : GateToPPMSemanticsModel)
    (lowering : PPMToBackendLoweringModel models sem)
    (b : VerifiedArithmeticPPMToSystemBlockV2 models sem lowering) :
    lowering.resourceAlignment
      b.arithmeticPPM.arithmetic.ppmProgram
      b.backend.schedule
defppmSpecsOfICXGate
def ppmSpecsOfICXGate : Gate → List PPMSpec
  | .I         => []
  | .X q       =>
      [{ measuredPauliKind
theoremppmSpecsOfICXGate_I
theorem ppmSpecsOfICXGate_I : ppmSpecsOfICXGate Gate.I = []
theoremppmSpecsOfICXGate_seq
theorem ppmSpecsOfICXGate_seq (g₁ g₂ : Gate) :
    ppmSpecsOfICXGate (Gate.seq g₁ g₂)
      = ppmSpecsOfICXGate g₁ ++ ppmSpecsOfICXGate g₂
structureICXPPMProgramSpecWitness
structure ICXPPMProgramSpecWitness
    (n : Nat) (program : PPMProgram) (specs : List PPMSpec)
A witness that a PPM program is the compilation of some ICX `Gate` AND its `PPMSpec` summary list.
defICXPPMProgramImplementsSpecs
def ICXPPMProgramImplementsSpecs
    (n : Nat) (program : PPMProgram) (specs : List PPMSpec) : Prop
The ICX-fragment PPM-program implements its `PPMSpec` summary list iff a witness exists. Not `True`; the witness packs four real fields including the §16 `ImplementsGateAsPPM` proof.
theoremcompileICXGateToPPM_implements_specs
theorem compileICXGateToPPM_implements_specs
    (n : Nat) (g : Gate) (hg : isICXGate g = true) :
    ICXPPMProgramImplementsSpecs n
      (compileArithmeticGateToPPM g) (ppmSpecsOfICXGate g)
defICXPartialLoweringModel
def ICXPartialLoweringModel
    (models : SystemModels) (n : Nat)
    (qecRel : List QECGadgetSpec → CompressedSchedule → Prop)
    (resRel : PPMProgram → CompressedSchedule → Prop) :
    PPMToBackendLoweringModel models (cxMacroPPMSemanticsModel n)
defVerifiedArithmeticPPMProgramBlock.ofICX
def VerifiedArithmeticPPMProgramBlock.ofICX
    (n : Nat) (g : Gate) (hg : isICXGate g = true)
    (qecSpecs : List QECGadgetSpec) :
    VerifiedArithmeticPPMProgramBlock (cxMacroPPMSemanticsModel n)
theoremVerifiedArithmeticPPMProgramBlock.ofICX_implements_specs
theorem VerifiedArithmeticPPMProgramBlock.ofICX_implements_specs
    (n : Nat) (g : Gate) (hg : isICXGate g = true)
    (qecSpecs : List QECGadgetSpec) :
    ICXPPMProgramImplementsSpecs n
      (VerifiedArithmeticPPMProgramBlock.ofICX n g hg qecSpecs).arithmetic.ppmProgram
      (VerifiedArithmeticPPMProgramBlock.ofICX n g hg qecSpecs).ppmSpecs
An ICX-fragment program block's PPM program implements its attached `PPMSpec` summary under `ICXPPMProgramImplementsSpecs`. This is the slot-filling theorem for `ICXPartialLoweringModel.ppmProgramImplementsSpecs`.
structurePPMProgramResourceSummary
structure PPMProgramResourceSummary

FormalRV.PPM.CircuitToPPMInterface.PPMBackendLoweringModel

FormalRV/PPM/CircuitToPPMInterface/PPMBackendLoweringModel.lean
defzero
def zero : PPMProgramResourceSummary
Zero summary — identity for `add`.
defadd
def add (a b : PPMProgramResourceSummary) : PPMProgramResourceSummary
Fieldwise addition.

FormalRV.PPM.CircuitToPPMInterface.SurgeryGadgetLoweringAndQECInstance

FormalRV/PPM/CircuitToPPMInterface/SurgeryGadgetLoweringAndQECInstance.lean
### §21.b Per-command counters and program summarizer.
defppmCommandMeasureCount
def ppmCommandMeasureCount : PPMCommand → Nat
  | .measurePauliKind _ _ => 1
  | _                     => 0
defppmCommandFrameUpdateCount
def ppmCommandFrameUpdateCount : PPMCommand → Nat
  | .applyFrameUpdate _ => 1
  | _                   => 0
defppmCommandMagicTCount
def ppmCommandMagicTCount : PPMCommand → Nat
  | .useMagicT _ => 1
  | _            => 0
deflistSumOver
def listSumOver {α : Type} (f : α → Nat) : List α → Nat
  | []      => 0
  | x :: xs => f x + listSumOver f xs
Sum a Nat-valued function over a list.
theoremlistSumOver_append
theorem listSumOver_append {α : Type} (f : α → Nat) (xs ys : List α) :
    listSumOver f (xs ++ ys) = listSumOver f xs + listSumOver f ys
defppmProgramResourceSummary
def ppmProgramResourceSummary (p : PPMProgram) : PPMProgramResourceSummary
theoremppmProgramResourceSummary_append
theorem ppmProgramResourceSummary_append (p₁ p₂ : PPMProgram) :
    ppmProgramResourceSummary (p₁ ++ p₂)
      = PPMProgramResourceSummary.add
          (ppmProgramResourceSummary p₁) (ppmProgramResourceSummary p₂)
theoremppmProgramResourceSummary_compile_I
theorem ppmProgramResourceSummary_compile_I :
    ppmProgramResourceSummary (compileArithmeticGateToPPM Gate.I)
      = PPMProgramResourceSummary.zero
theoremppmProgramResourceSummary_compile_X
theorem ppmProgramResourceSummary_compile_X (q : LogicalQubitId) :
    ppmProgramResourceSummary (compileArithmeticGateToPPM (Gate.X q))
      = PPMProgramResourceSummary.mk 1 0 1 0
theoremppmProgramResourceSummary_compile_CX
theorem ppmProgramResourceSummary_compile_CX (c t : LogicalQubitId) :
    ppmProgramResourceSummary (compileArithmeticGateToPPM (Gate.CX c t))
      = PPMProgramResourceSummary.mk 2 1 1 0
theoremppmProgramResourceSummary_compile_CCX
theorem ppmProgramResourceSummary_compile_CCX (a b t : LogicalQubitId) :
    ppmProgramResourceSummary (compileArithmeticGateToPPM (Gate.CCX a b t))
      = PPMProgramResourceSummary.mk 3 1 1 1
theoremppmProgramResourceSummary_compile_seq
theorem ppmProgramResourceSummary_compile_seq (g₁ g₂ : Gate) :
    ppmProgramResourceSummary (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
      = PPMProgramResourceSummary.add
          (ppmProgramResourceSummary (compileArithmeticGateToPPM g₁))
          (ppmProgramResourceSummary (compileArithmeticGateToPPM g₂))
defICXResourceAlignment
def ICXResourceAlignment
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (program : PPMProgram) (schedule : CompressedSchedule) : Prop
defICXResourceLoweringModel
def ICXResourceLoweringModel
    (models : SystemModels) (n : Nat)
    (qecRel : List QECGadgetSpec → CompressedSchedule → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary) :
    PPMToBackendLoweringModel models (cxMacroPPMSemanticsModel n)
theoremVerifiedArithmeticPPMProgramBlock.ofICX_resourceAlignment
theorem VerifiedArithmeticPPMProgramBlock.ofICX_resourceAlignment
    (models : SystemModels) (n : Nat)
    (g : Gate) (hg : isICXGate g = true)
    (qecSpecs : List QECGadgetSpec)
    (qecRel : List QECGadgetSpec → CompressedSchedule → Prop)
    (backend : VerifiedBackendBlock models)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM g)) :
    (ICXResourceLoweringModel models n qecRel backendSummary).resourceAlignment
      (VerifiedArithmeticPPMProgramBlock.ofICX n g hg qecSpecs).arithmetic.ppmProgram
If the user-supplied `backendSummary backend.schedule` equals the PPM-program resource summary of the compiled ICX gate, then the `resourceAlignment` slot of `ICXResourceLoweringModel` is satisfied by the `VerifiedArithmeticPPMProgramBlock.ofICX` block on `backend`.
defspecMatchListwise
def specMatchListwise
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop) :
    List QECGadgetSpec → List SchedulableSurgeryGadget → Prop
  | [],      []      => True
  | _ :: _,  []      => False
  | [],      _ :: _  => False
  | q :: qs, g :: gs => specMatch q g ∧ specMatchListwise specMatch qs gs
Listwise spec-matching between a list of `QECGadgetSpec`s and a list of `SchedulableSurgeryGadget`s. Equivalent to `List.Forall₂` (which Lean core does not expose). Structural recursion on the two lists; matches by position.
structureSurgeryGadgetBackendLoweringWitness
structure SurgeryGadgetBackendLoweringWitness
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpec : QECGadgetSpec) (schedule : CompressedSchedule)
One-gadget structural witness: a single `SchedulableSurgeryGadget` compiled to a `SysCall` list, wrapped as a `CompressedSchedule.atom`, that is claimed to implement a single `QECGadgetSpec` via the supplied `specMatch`.
defSurgeryQECSpecLowerToScheduleOne
def SurgeryQECSpecLowerToScheduleOne
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpec : QECGadgetSpec) (schedule : CompressedSchedule) : Prop
Single-spec, single-gadget lowering relation.
defcomposedSurgerySchedule
def composedSurgerySchedule
    (gadgets : List SchedulableSurgeryGadget) : CompressedSchedule
Build a `CompressedSchedule` by composing each gadget's compiled SysCall list as an `atom`, then sequencing all such atoms via `CompressedSchedule.seq`.
defSurgeryQECSpecsLowerToSchedule
def SurgeryQECSpecsLowerToSchedule
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpecs : List QECGadgetSpec) (schedule : CompressedSchedule) : Prop
List version of the lowering relation. The `qecSpecs` list lowers to `schedule` iff there exists a matching list of `SchedulableSurgeryGadget`s that pointwise pass `specMatch`, and `schedule` is the `composedSurgerySchedule` of those gadgets.
theoremSurgeryQECSpecLowerToScheduleOne.construct
theorem SurgeryQECSpecLowerToScheduleOne.construct
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpec : QECGadgetSpec) (gadget : SchedulableSurgeryGadget)
    (hmatch : specMatch qecSpec gadget) :
    SurgeryQECSpecLowerToScheduleOne specMatch qecSpec
      (CompressedSchedule.atom (compileSurgeryGadgetToSysCalls gadget))
Single-gadget witness construction: given a `specMatch` proof and a compile equation, the one-gadget lowering relation holds for the corresponding `CompressedSchedule.atom`.
theoremSurgeryQECSpecsLowerToSchedule.construct
theorem SurgeryQECSpecsLowerToSchedule.construct
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpecs : List QECGadgetSpec) (gadgets : List SchedulableSurgeryGadget)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets) :
    SurgeryQECSpecsLowerToSchedule specMatch qecSpecs
      (composedSurgerySchedule gadgets)
List witness construction: from a list of gadgets with pointwise `specMatch` proofs, the list lowering relation holds for the `composedSurgerySchedule`.
theoremSurgeryQECSpecsLowerToSchedule.nil
theorem SurgeryQECSpecsLowerToSchedule.nil
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop) :
    SurgeryQECSpecsLowerToSchedule specMatch []
      (composedSurgerySchedule [])
Trivial nil case: empty `qecSpecs` and empty `gadgets` produce the empty `composedSurgerySchedule`.
defICXSurgeryLoweringModel
def ICXSurgeryLoweringModel
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary) :
    PPMToBackendLoweringModel models (cxMacroPPMSemanticsModel n)
defVerifiedArithmeticPPMToSystemBlockV2.ofICXSurgery
def VerifiedArithmeticPPMToSystemBlockV2.ofICXSurgery
    (models : SystemModels) (n : Nat)
    (g : Gate) (hg : isICXGate g = true) (qecSpecs : List QECGadgetSpec)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (backend : VerifiedBackendBlock models)
    (hqec :
      SurgeryQECSpecsLowerToSchedule specMatch qecSpecs backend.schedule)
    (hres :
      ICXResourceAlignment backendSummary
        ((VerifiedArithmeticPPMProgramBlock.ofICX n g hg qecSpecs).arithmetic.ppmProgram)
        backend.schedule) :
deftoyICXGate
def toyICXGate : Gate
theoremtoyICXGate_isICX
theorem toyICXGate_isICX : isICXGate toyICXGate = true
deftoyArithmeticPPMBlock
def toyArithmeticPPMBlock (n : Nat) (qecSpecs : List QECGadgetSpec) :
    VerifiedArithmeticPPMProgramBlock (cxMacroPPMSemanticsModel n)
theoremtoyArithmeticPPMBlock_implements_specs
theorem toyArithmeticPPMBlock_implements_specs
    (n : Nat) (qecSpecs : List QECGadgetSpec) :
    ICXPPMProgramImplementsSpecs n
      (toyArithmeticPPMBlock n qecSpecs).arithmetic.ppmProgram
      (toyArithmeticPPMBlock n qecSpecs).ppmSpecs
Sanity: `toyArithmeticPPMBlock` implements its own PPM spec list under `ICXPPMProgramImplementsSpecs`.
theoremtoy_qec_backend_ok
theorem toy_qec_backend_ok
    (models : SystemModels)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (backend : VerifiedBackendBlock models)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets) :
    SurgeryQECSpecsLowerToSchedule specMatch qecSpecs backend.schedule
theoremtoy_resource_alignment_ok
theorem toy_resource_alignment_ok
    (models : SystemModels) (n : Nat)
    (qecSpecs : List QECGadgetSpec)
    (backend : VerifiedBackendBlock models)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
    ICXResourceAlignment backendSummary
      ((toyArithmeticPPMBlock n qecSpecs).arithmetic.ppmProgram)
      backend.schedule
deftoyV2Block
def toyV2Block
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
theoremtoyICXBlock_system_invariants_ok
theorem toyICXBlock_system_invariants_ok
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
theoremtoyICXBlock_ppm_semantic
theorem toyICXBlock_ppm_semantic
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
theoremtoyICXBlock_qec_backend
theorem toyICXBlock_qec_backend
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
theoremtoyICXBlock_resource_alignment
theorem toyICXBlock_resource_alignment
    (models : SystemModels) (n : Nat)
    (specMatch : QECGadgetSpec → SchedulableSurgeryGadget → Prop)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch : specMatchListwise specMatch qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
defQECSpecMatchesSurgeryGadget
def QECSpecMatchesSurgeryGadget
    (spec : QECGadgetSpec) (sg : SchedulableSurgeryGadget) : Prop
theoremQECSpecMatchesSurgeryGadget.tau_s_eq
theorem QECSpecMatchesSurgeryGadget.tau_s_eq
    {spec : QECGadgetSpec} {sg : SchedulableSurgeryGadget}
    (h : QECSpecMatchesSurgeryGadget spec sg) :
    spec.gadget.tau_s = sg.gadget.tau_s
theoremQECSpecMatchesSurgeryGadget.code_eq
theorem QECSpecMatchesSurgeryGadget.code_eq
    {spec : QECGadgetSpec} {sg : SchedulableSurgeryGadget}
    (h : QECSpecMatchesSurgeryGadget spec sg) :
    spec.code = sg.gadget.data_code
theoremQECSpecMatchesSurgeryGadget.target_eq
theorem QECSpecMatchesSurgeryGadget.target_eq
    {spec : QECGadgetSpec} {sg : SchedulableSurgeryGadget}
    (h : QECSpecMatchesSurgeryGadget spec sg) :
    spec.gadget.target = sg.gadget.data_code
theoremQECSpecMatchesSurgeryGadget.syndromeRounds_eq
theorem QECSpecMatchesSurgeryGadget.syndromeRounds_eq
    {spec : QECGadgetSpec} {sg : SchedulableSurgeryGadget}
    (h : QECSpecMatchesSurgeryGadget spec sg) :
    spec.syndromeRounds = sg.gadget.tau_s
theoremQECSpecMatchesSurgeryGadget.decoder_eq
theorem QECSpecMatchesSurgeryGadget.decoder_eq
    {spec : QECGadgetSpec} {sg : SchedulableSurgeryGadget}
    (h : QECSpecMatchesSurgeryGadget spec sg) :
    spec.decoder = sg.decoder_id_base
defICXConcreteSurgeryLoweringModel
def ICXConcreteSurgeryLoweringModel
    (models : SystemModels) (n : Nat)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary) :
    PPMToBackendLoweringModel models (cxMacroPPMSemanticsModel n)
theoremtoy_qec_backend_ok_concrete
theorem toy_qec_backend_ok_concrete
    (models : SystemModels)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (hmatch :
      specMatchListwise QECSpecMatchesSurgeryGadget qecSpecs gadgets)
    (backend : VerifiedBackendBlock models)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets) :
    SurgeryQECSpecsLowerToSchedule QECSpecMatchesSurgeryGadget qecSpecs
      backend.schedule
deftoyV2BlockConcreteSpecMatch
def toyV2BlockConcreteSpecMatch
    (models : SystemModels) (n : Nat)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch :
      specMatchListwise QECSpecMatchesSurgeryGadget qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
theoremtoyICXBlockConcreteSpecMatch_system_invariants_ok
theorem toyICXBlockConcreteSpecMatch_system_invariants_ok
    (models : SystemModels) (n : Nat)
    (backendSummary : CompressedSchedule → PPMProgramResourceSummary)
    (qecSpecs : List QECGadgetSpec)
    (gadgets : List SchedulableSurgeryGadget)
    (backend : VerifiedBackendBlock models)
    (hmatch :
      specMatchListwise QECSpecMatchesSurgeryGadget qecSpecs gadgets)
    (hbackend : backend.schedule = composedSurgerySchedule gadgets)
    (hAlign :
      backendSummary backend.schedule
        = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)) :
deftoyQECCode
def toyQECCode : QECCode
deftoyPPMGadget
def toyPPMGadget : PPMGadget
deftoyPPMSpec
def toyPPMSpec : PPMSpec
deftoyQECGadgetSpec
def toyQECGadgetSpec : QECGadgetSpec
deftoyLDPCSurgeryGadget
def toyLDPCSurgeryGadget : LDPC.SurgeryGadget
deftoySchedulableSurgeryGadget
def toySchedulableSurgeryGadget : SchedulableSurgeryGadget
theoremtoy_QECSpecMatchesSurgeryGadget
theorem toy_QECSpecMatchesSurgeryGadget :
    QECSpecMatchesSurgeryGadget
      toyQECGadgetSpec
      toySchedulableSurgeryGadget
theoremtoy_specMatchListwise_singleton
theorem toy_specMatchListwise_singleton :
    specMatchListwise
      QECSpecMatchesSurgeryGadget
      [toyQECGadgetSpec]
      [toySchedulableSurgeryGadget]
theoremtoy_singleton_qec_backend_lowering
theorem toy_singleton_qec_backend_lowering :
    SurgeryQECSpecsLowerToSchedule
      QECSpecMatchesSurgeryGadget
      [toyQECGadgetSpec]
      (composedSurgerySchedule [toySchedulableSurgeryGadget])
deftoySurgerySysCalls
def toySurgerySysCalls : List SysCall
deftoySurgeryAtomSchedule
def toySurgeryAtomSchedule : CompressedSchedule
theoremtoySurgerySysCalls_length
theorem toySurgerySysCalls_length : toySurgerySysCalls.length = 6
Length witness: the toy gadget has `tau_s = 1`, so the compiler emits `5·1 + 1 = 6` SysCalls.
deftoySurgeryAncillaModel
def toySurgeryAncillaModel : AncillaModel
deftoySurgerySystemModels
def toySurgerySystemModels : SystemModels
deftoySurgeryComposedSchedule
def toySurgeryComposedSchedule : CompressedSchedule
Composed-form schedule (a `.seq [.atom …]`) matching `composedSurgerySchedule [toySchedulableSurgeryGadget]` by definition. This is the form the §22 `composedSurgerySchedule` builder expects; it differs from the §25.g `toySurgeryAtomSchedule` (a plain `.atom …`) only in being wrapped under one extra `.seq` constructor.
theoremtoySurgeryBackendCert
theorem toySurgeryBackendCert :
    compressed_schedule_strict_certificate_ok
      toySurgerySystemModels
      toySurgeryComposedSchedule = true
deftoySurgeryVerifiedBackendBlock
def toySurgeryVerifiedBackendBlock :
    VerifiedBackendBlock toySurgerySystemModels
theoremtoySurgeryBackendBlock_strict_invariants_ok
theorem toySurgeryBackendBlock_strict_invariants_ok :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        toySurgerySystemModels.arch
        toySurgerySystemModels.opCap
        toySurgerySystemModels.slotCap
        toySurgerySystemModels.ancillaModel
        toySurgeryVerifiedBackendBlock.schedule.expand
        toySurgerySystemModels.t_react_us
        toySurgerySystemModels.window_us
        toySurgerySystemModels.max_per_window = true
theoremtoySurgeryVerifiedBackendBlock_schedule_eq_composed
theorem toySurgeryVerifiedBackendBlock_schedule_eq_composed :
    toySurgeryVerifiedBackendBlock.schedule
      = composedSurgerySchedule [toySchedulableSurgeryGadget]
The toy backend block's schedule equals the composed surgery schedule of the toy gadget list, by definition.
deftoyConstantBackendSummary
def toyConstantBackendSummary :
    CompressedSchedule → PPMProgramResourceSummary
A constant-valued backend summary that aligns with the toy ICX gate's resource summary by definition.
theoremtoyConstantBackendSummary_alignment
theorem toyConstantBackendSummary_alignment :
    toyConstantBackendSummary toySurgeryVerifiedBackendBlock.schedule
      = ppmProgramResourceSummary (compileArithmeticGateToPPM toyICXGate)
deftoyConcreteEndToEndV2Block
def toyConcreteEndToEndV2Block (n : Nat) :
    VerifiedArithmeticPPMToSystemBlockV2 toySurgerySystemModels
      (cxMacroPPMSemanticsModel n)
      (ICXConcreteSurgeryLoweringModel toySurgerySystemModels n
        toyConstantBackendSummary)
theoremtoyConcreteEndToEnd_system_invariants_ok
theorem toyConcreteEndToEnd_system_invariants_ok (n : Nat) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        toySurgerySystemModels.arch
        toySurgerySystemModels.opCap
        toySurgerySystemModels.slotCap
        toySurgerySystemModels.ancillaModel
        toySurgeryVerifiedBackendBlock.schedule.expand
        toySurgerySystemModels.t_react_us
        toySurgerySystemModels.window_us
        toySurgerySystemModels.max_per_window = true
inductiveSurgeryObs
inductive SurgeryObs
defsyscallToSurgeryObs?
def syscallToSurgeryObs? : SysCall → Option SurgeryObs
  | { kind
Project a single SysCall to its surgery observation. `Gate1q`, `TransitQubit`, `RequestMagicState` are NOT part of the surgery shape — they map to `none` and get filtered out.
defsurgeryTraceOfSysCalls
def surgeryTraceOfSysCalls (xs : List SysCall) : List SurgeryObs
defsurgeryTraceOfCompressedSchedule
def surgeryTraceOfCompressedSchedule (cs : CompressedSchedule) : List SurgeryObs
defexpectedSingleRoundTrace
def expectedSingleRoundTrace (g : SchedulableSurgeryGadget) :
    List SurgeryObs
The expected trace for one `tau_s = 1` surgery round plus its trailing frame update. Lines up exactly with `compileSurgeryGadgetToSysCalls` for `tau_s = 1`.
defSurgeryTraceMatchesGadget
def SurgeryTraceMatchesGadget
    (g : SchedulableSurgeryGadget) (tr : List SurgeryObs) : Prop
The trace predicate: the observed trace must equal the expected single-round trace exactly. Single-round only — multi-round (`tau_s > 1`) gadgets are not covered by this predicate.
instanceg
instance (g : SchedulableSurgeryGadget) (tr : List SurgeryObs) :
    Decidable (SurgeryTraceMatchesGadget g tr)
theoremtoySurgeryTraceMatchesGadget
theorem toySurgeryTraceMatchesGadget :
    SurgeryTraceMatchesGadget toySchedulableSurgeryGadget
      (surgeryTraceOfSysCalls toySurgerySysCalls)
theoremtoySurgeryComposedSchedule_trace_matches
theorem toySurgeryComposedSchedule_trace_matches :
    SurgeryTraceMatchesGadget toySchedulableSurgeryGadget
      (surgeryTraceOfCompressedSchedule
        toySurgeryVerifiedBackendBlock.schedule)
structureSurgeryQECTraceLoweringEvidence
structure SurgeryQECTraceLoweringEvidence
    (spec : QECGadgetSpec) (g : SchedulableSurgeryGadget)
    (sched : CompressedSchedule) : Prop

FormalRV.PPM.CircuitToPPMMagicFactory

FormalRV/PPM/CircuitToPPMMagicFactory.lean
FormalRV.Framework.CircuitToPPMMagicFactory — abstract PPM-level T-factory + magic-token interface. ## Scope (E21) This file introduces an HONEST abstraction layer for a T-factory operating at the PPM/logical level: `TFactoryContract` — a parametric factory contract (output kind, latency, footprint, success-probability lower bound, output-error upper bound, herald flag), with a `WellFormed` predicate. `MagicToken` and `FactoryOutcome` — typed magic tokens and the success / herald-fail / unherald-fail outcome sum. `MagicBasisPPMState` — the basisPPM state of E20 extended with a pool of certified tokens and a `failed` flag, plus projection back to `BasisPPMState`. `magicBasisPPMSemanticsModel F` — a magic-aware semantic model that lifts the E20 ICX soundness / reflection to the magic state space; `useMagicT` consumes one certified T token; `CCX` remains structurally `False` (not realised here). `magicBasisRefinesApplyNat F` — the concrete `PPMRefinesApplyNat` bridge. `magicRequestCount` — the magic-T-request count of a `PPMProgram` and its lemmas (using the existing `ppmCommandMagicTCount` from `CircuitToPPMInterface.lean §21`). `allMagicRequestsSuccessProbLB` — Nat-scaled success-probability lower-bound accounting. `TFactoryToffoliObligation F` — the named future obligation: a magic-using PPM program for `Gate.CCX` that is sound under `magicBasisPPMSemanticsModel F`. NOT instantiated here. ## Honesty boundary This file does NOT prove: Physical T-state distillation correctness. Gate teleportation correctness. CCX / Toffoli correctness (the current compiler emits one `useMagicT` for `Gate.CCX` which is a placeholder resource count, not a Toffoli decomposition; we explicitly note this). Full Shor success-probability correctness. QEC / surgery / backend implementation of magic factories. The success-probability accounting uses Nat-scaled parts-per-million / per-Q-fold representations, NOT real numbers; this matches the existing `AtomicFactorySpec`'s `success_probability_ppm` convention in `FactoryHierarchy.lean`.
structureTFactoryContract
structure TFactoryContract
Abstract T-factory contract at the PPM layer. Nat-scaled probabilities (ppm = parts per million; 1_000_000 = 100%).
defTFactoryContract.WellFormed
def TFactoryContract.WellFormed (F : TFactoryContract) : Prop
Well-formedness for a `TFactoryContract`: it must produce `T` states, and the ppm fields must lie in `[0, 10^6]`.
structureMagicToken
structure MagicToken
A typed magic token issued by a specific factory. The `certified` flag records whether post-distillation acceptance/verification passed.
inductiveFactoryOutcome
inductive FactoryOutcome
A factory's nondeterministic outcome. We expose three branches: success (with a token), heralded failure (factory signals failure), and unheralded failure (silent error — accepted under false certification).
defMagicToken.IsCertifiedTFrom
def MagicToken.IsCertifiedTFrom
    (F : TFactoryContract) (tok : MagicToken) : Prop
A token is a certified-T from `F` iff its factory id and kind match `F`'s and `certified = true`.
structureMagicBasisPPMState
structure MagicBasisPPMState : Type
instanceInhabited
instance : Inhabited MagicBasisPPMState
defMagicBasisPPMState.toBasis
def MagicBasisPPMState.toBasis (s : MagicBasisPPMState) : BasisPPMState
Forget the magic pool and failure flag, returning the underlying basis state.
defBasisPPMState.withEmptyMagic
def BasisPPMState.withEmptyMagic (s : BasisPPMState) : MagicBasisPPMState
Lift a `BasisPPMState` to a `MagicBasisPPMState` with no tokens and no failure.
defhasCertifiedT
def hasCertifiedT (F : TFactoryContract) (s : MagicBasisPPMState) : Prop
The state holds at least one certified-T token from `F`.
defconsumeCertifiedT
def consumeCertifiedT
    (F : TFactoryContract) (s t : MagicBasisPPMState) : Prop
Consume one certified-T token from `s.magicPool`, incrementing `magicUsed` and preserving bits. No failure: `failed` flag remains `false`. This is the success branch of a T-supply call.
defrequestTSuccess
def requestTSuccess
    (F : TFactoryContract)
    (s t : MagicBasisPPMState) (tok : MagicToken) : Prop
Request the factory to supply a new certified-T token on the success branch: prepends `tok` to the pool, leaves everything else unchanged.
defmagicRequestCount
def magicRequestCount (p : PPMProgram) : Nat
Number of `useMagicT` requests in a `PPMProgram`. Reuses the existing per-command counter from §21.b of `CircuitToPPMInterface.lean`.
theoremmagicRequestCount_nil
theorem magicRequestCount_nil : magicRequestCount [] = 0
theoremmagicRequestCount_append
theorem magicRequestCount_append (p q : PPMProgram) :
    magicRequestCount (p ++ q)
      = magicRequestCount p + magicRequestCount q
theoremmagicRequestCount_compile_I
theorem magicRequestCount_compile_I :
    magicRequestCount (compileArithmeticGateToPPM Gate.I) = 0
theoremmagicRequestCount_compile_X
theorem magicRequestCount_compile_X (q : Nat) :
    magicRequestCount (compileArithmeticGateToPPM (Gate.X q)) = 0
theoremmagicRequestCount_compile_CX
theorem magicRequestCount_compile_CX (c t : Nat) :
    magicRequestCount (compileArithmeticGateToPPM (Gate.CX c t)) = 0
theoremmagicRequestCount_compile_CCX
theorem magicRequestCount_compile_CCX (a b c : Nat) :
    magicRequestCount (compileArithmeticGateToPPM (Gate.CCX a b c)) = 1
theoremmagicRequestCount_compile_ICX
theorem magicRequestCount_compile_ICX :
    ∀ g, isICXGate g = true →
      magicRequestCount (compileArithmeticGateToPPM g) = 0
ICX gates have zero magic-T requests in their compiled PPM program.
defallMagicRequestsSuccessProbLB
def allMagicRequestsSuccessProbLB
    (F : TFactoryContract) (k : Nat) : Nat
Nat-scaled success-probability lower bound for `k` independent factory invocations: `(p_LB)^k` in ppm-units. Closed-form placeholder; not used as a real bound (which would need a `Rat`/`Real` story).
theoremallMagicRequestsSuccessProbLB_zero
theorem allMagicRequestsSuccessProbLB_zero (F : TFactoryContract) :
    allMagicRequestsSuccessProbLB F 0 = 1
theoremallMagicRequestsSuccessProbLB_succ
theorem allMagicRequestsSuccessProbLB_succ (F : TFactoryContract) (k : Nat) :
    allMagicRequestsSuccessProbLB F (k + 1)
      = allMagicRequestsSuccessProbLB F k * F.successProbLB_ppm
defmagicBasisPPMCommandRel
def magicBasisPPMCommandRel
    (F : TFactoryContract) :
    PPMCommand → MagicBasisPPMState → MagicBasisPPMState → Prop
  | .applyFrameUpdate qs, s, t =>
      t.bits = qs.foldl (fun bs q => update bs q (!bs q)) s.bits
      ∧ t.magicUsed = s.magicUsed
      ∧ t.magicPool = s.magicPool
      ∧ t.failed    = s.failed
  | .measurePauliKind PauliKind.Z [c, tgt], s, t =>
      t.bits = update s.bits tgt (xor (s.bits tgt) (!s.bits c))
      ∧ t.magicUsed = s.magicUsed
      ∧ t.magicPool = s.magicPool
The magic-aware command relation. For ICX commands (`applyFrameUpdate`, `measurePauliKind`) it lifts the E20 `basisPPMCommandRel` action on `bits`, preserving `magicPool` and `failed`. `useMagicT q` consumes one certified-T token from the pool.
defmagicBasisPPMGateRel
def magicBasisPPMGateRel : Gate → MagicBasisPPMState → MagicBasisPPMState → Prop
  | .I,         s, t => t = s
  | .X q,       s, t =>
      t.bits = update s.bits q (!s.bits q)
      ∧ t.magicUsed = s.magicUsed
      ∧ t.magicPool = s.magicPool
      ∧ t.failed    = s.failed
  | .CX c tgt,  s, t =>
      t.bits = update s.bits tgt (xor (s.bits tgt) (s.bits c))
      ∧ t.magicUsed = s.magicUsed
      ∧ t.magicPool = s.magicPool
      ∧ t.failed    = s.failed
defmagicBasisPPMSemanticsModel
def magicBasisPPMSemanticsModel (F : TFactoryContract) : GateToPPMSemanticsModel
theoremmagicBasisPPM_I_sound
theorem magicBasisPPM_I_sound (F : TFactoryContract) :
    ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) Gate.I
      (compileArithmeticGateToPPM Gate.I)
theoremmagicBasisPPM_X_sound
theorem magicBasisPPM_X_sound (F : TFactoryContract) (q : Nat) :
    ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
theoremmagicBasisPPM_CX_sound
theorem magicBasisPPM_CX_sound (F : TFactoryContract) (c tgt : Nat) :
    ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
theoremmagicBasisPPM_seq_sound
theorem magicBasisPPM_seq_sound (F : TFactoryContract) (g₁ g₂ : Gate)
    (h₁ : ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) g₁
            (compileArithmeticGateToPPM g₁))
    (h₂ : ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) g₂
            (compileArithmeticGateToPPM g₂)) :
    ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) (Gate.seq g₁ g₂)
      (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
theoremmagicBasisPPMSound_ICX
theorem magicBasisPPMSound_ICX (F : TFactoryContract) :
    ∀ g, isICXGate g = true →
      ImplementsGateAsPPM (magicBasisPPMSemanticsModel F) g
        (compileArithmeticGateToPPM g)
theoremmagicBasisPPM_I_reflects
theorem magicBasisPPM_I_reflects (F : TFactoryContract) :
    PPMReflectsGateRel (magicBasisPPMSemanticsModel F) Gate.I
      (compileArithmeticGateToPPM Gate.I)
theoremmagicBasisPPM_X_reflects
theorem magicBasisPPM_X_reflects (F : TFactoryContract) (q : Nat) :
    PPMReflectsGateRel (magicBasisPPMSemanticsModel F) (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
theoremmagicBasisPPM_CX_reflects
theorem magicBasisPPM_CX_reflects (F : TFactoryContract) (c tgt : Nat) :
    PPMReflectsGateRel (magicBasisPPMSemanticsModel F) (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
theoremmagicBasisPPM_seq_reflects
theorem magicBasisPPM_seq_reflects (F : TFactoryContract) (g₁ g₂ : Gate)
    (h₁ : PPMReflectsGateRel (magicBasisPPMSemanticsModel F) g₁
            (compileArithmeticGateToPPM g₁))
    (h₂ : PPMReflectsGateRel (magicBasisPPMSemanticsModel F) g₂
            (compileArithmeticGateToPPM g₂)) :
    PPMReflectsGateRel (magicBasisPPMSemanticsModel F) (Gate.seq g₁ g₂)
      (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
theoremmagicBasisPPMReflects_ICX
theorem magicBasisPPMReflects_ICX (F : TFactoryContract) :
    ∀ g, isICXGate g = true →
      PPMReflectsGateRel (magicBasisPPMSemanticsModel F) g
        (compileArithmeticGateToPPM g)
defmagicBasisEncodeBits
def magicBasisEncodeBits (F : TFactoryContract) (f : Nat → Bool) :
    (magicBasisPPMSemanticsModel F).State
Encoder parametric in the contract `F`. The factory parameter affects only the `ppmCommandRel` interpretation of `useMagicT`; encoded states are the same.
defmagicBasisObservesBits
def magicBasisObservesBits (F : TFactoryContract)
    (s : (magicBasisPPMSemanticsModel F).State)
    (f : Nat → Bool) : Prop
A magic-aware state observes a bit-state iff its `bits` field matches and the `failed` flag is `false`.
theoremmagicBasisEncode_observes
theorem magicBasisEncode_observes (F : TFactoryContract) (f : Nat → Bool) :
    magicBasisObservesBits F (magicBasisEncodeBits F f) f
theoremmagicBasisPPMGateRel_imp_applyNat
theorem magicBasisPPMGateRel_imp_applyNat
    (g : Gate) :
    ∀ (s σ' : MagicBasisPPMState),
      magicBasisPPMGateRel g s σ' → σ'.bits = Gate.applyNat g s.bits
Generalised statement: any `magicBasisPPMGateRel` transition produces a target state whose `bits` field equals `Gate.applyNat g` applied to the source's bits. CCX is `False` in this gate relation, so the case closes vacuously.
theoremmagicBasisPPMGateRel_preserves_failed
theorem magicBasisPPMGateRel_preserves_failed
    (g : Gate) :
    ∀ (s σ' : MagicBasisPPMState),
      magicBasisPPMGateRel g s σ' → σ'.failed = s.failed
Similarly preserve the `failed` flag through any `magicBasisPPMGateRel` transition. Required because `magicBasisObservesBits` checks `failed = false`.
theoremmagicBasisGateRel_applyNat_obs
theorem magicBasisGateRel_applyNat_obs (F : TFactoryContract)
    (g : Gate) (f : Nat → Bool)
    (σ' : (magicBasisPPMSemanticsModel F).State)
    (h : (magicBasisPPMSemanticsModel F).gateRel g
            (magicBasisEncodeBits F f) σ') :
    magicBasisObservesBits F σ' (Gate.applyNat g f)
defmagicBasisRefinesApplyNat
def magicBasisRefinesApplyNat (F : TFactoryContract) :
    PPMRefinesApplyNat (magicBasisPPMSemanticsModel F)
theoremcompileICXGateToPPM_applyNat_bridge_magicBasisPPM
theorem compileICXGateToPPM_applyNat_bridge_magicBasisPPM
    (F : TFactoryContract) (g : Gate) (hICX : isICXGate g = true) :
    LogicalGateAsPPMApplyNat (magicBasisPPMSemanticsModel F)
      (magicBasisRefinesApplyNat F) g
theoremshor_arithmetic_ICX_correctness_transfers_to_magicBasisPPM
theorem shor_arithmetic_ICX_correctness_transfers_to_magicBasisPPM
    (F : TFactoryContract)
    (g : Gate) (hICX : isICXGate g = true)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (σ' : (magicBasisPPMSemanticsModel F).State)
    (hrun :
      PPMProgramRel (magicBasisPPMSemanticsModel F)
        (compileArithmeticGateToPPM g)
        ((magicBasisRefinesApplyNat F).encodeBits input)
        σ')
    (hGateCorrect : decode (Gate.applyNat g input) = expected) :
structureTFactoryToffoliObligation
structure TFactoryToffoliObligation
    (F : TFactoryContract)
defObservesCCXApplyNat
def ObservesCCXApplyNat
    (F : TFactoryContract) (a b c : Nat)
    (input : Nat → Bool)
    (σ' : (magicBasisPPMSemanticsModel F).State) : Prop
`σ'` observes the Boolean-`Gate.CCX a b c` image of `input` in the magic-aware model. Used as the direct semantic target of a non-vacuous Toffoli obligation.
structureTFactoryToffoliObligationV2
structure TFactoryToffoliObligationV2 (F : TFactoryContract)
theoremtoffoli_obligationV2_decoder_transfer
theorem toffoli_obligationV2_decoder_transfer
    (F : TFactoryContract)
    (obl : TFactoryToffoliObligationV2 F)
    (a b c : Nat)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (σ' : (magicBasisPPMSemanticsModel F).State)
    (hrun :
      PPMProgramRel (magicBasisPPMSemanticsModel F)
        (obl.ccx_program a b c)
        ((magicBasisRefinesApplyNat F).encodeBits input) σ')
    (hGateCorrect :
defcompileArithmeticGateToPPMWithToffoli
def compileArithmeticGateToPPMWithToffoli
    (F : TFactoryContract)
    (obl : TFactoryToffoliObligationV2 F) :
    Gate → PPMProgram
  | Gate.I         => compileArithmeticGateToPPM Gate.I
  | Gate.X q       => compileArithmeticGateToPPM (Gate.X q)
  | Gate.CX c t    => compileArithmeticGateToPPM (Gate.CX c t)
  | Gate.CCX a b c => obl.ccx_program a b c
  | Gate.seq g₁ g₂ =>
      compileArithmeticGateToPPMWithToffoli F obl g₁
        ++ compileArithmeticGateToPPMWithToffoli F obl g₂
A compiler that emits the same PPM program as `compileArithmeticGateToPPM` on ICX gates (so ICX soundness/reflection from §9 carries over), and uses the V2 obligation's `ccx_program` on CCX. Recurses on `seq` by concatenation.
theoremcompileArithmeticGateToPPMWithToffoli_applyNat_sound_from_observed
theorem compileArithmeticGateToPPMWithToffoli_applyNat_sound_from_observed
    (F : TFactoryContract)
    (obl : TFactoryToffoliObligationV2 F) :
    ∀ (g : Gate) (input : Nat → Bool)
      (s σ' : (magicBasisPPMSemanticsModel F).State),
      (magicBasisRefinesApplyNat F).observesBits s input →
      PPMProgramRel (magicBasisPPMSemanticsModel F)
        (compileArithmeticGateToPPMWithToffoli F obl g) s σ' →
      (magicBasisRefinesApplyNat F).observesBits σ'
        (Gate.applyNat g input)
theoremcompileArithmeticGateToPPMWithToffoli_applyNat_sound
theorem compileArithmeticGateToPPMWithToffoli_applyNat_sound
    (F : TFactoryContract)
    (obl : TFactoryToffoliObligationV2 F)
    (g : Gate) (input : Nat → Bool)
    (σ' : (magicBasisPPMSemanticsModel F).State)
    (hrun :
      PPMProgramRel (magicBasisPPMSemanticsModel F)
        (compileArithmeticGateToPPMWithToffoli F obl g)
        ((magicBasisRefinesApplyNat F).encodeBits input) σ') :
    (magicBasisRefinesApplyNat F).observesBits σ'
      (Gate.applyNat g input)
theoremshor_arithmetic_full_correctness_transfers_to_magicPPM_from_ToffoliObligation
theorem shor_arithmetic_full_correctness_transfers_to_magicPPM_from_ToffoliObligation
    (F : TFactoryContract)
    (obl : TFactoryToffoliObligationV2 F)
    (g : Gate)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (σ' : (magicBasisPPMSemanticsModel F).State)
    (hrun :
      PPMProgramRel (magicBasisPPMSemanticsModel F)
        (compileArithmeticGateToPPMWithToffoli F obl g)
        ((magicBasisRefinesApplyNat F).encodeBits input) σ')
    (hGateCorrect : decode (Gate.applyNat g input) = expected) :
theoremmagicRequestCount_compileWithToffoli_I
theorem magicRequestCount_compileWithToffoli_I
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) :
    magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl Gate.I) = 0
theoremmagicRequestCount_compileWithToffoli_X
theorem magicRequestCount_compileWithToffoli_X
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) (q : Nat) :
    magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl (Gate.X q)) = 0
theoremmagicRequestCount_compileWithToffoli_CX
theorem magicRequestCount_compileWithToffoli_CX
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) (c t : Nat) :
    magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl (Gate.CX c t)) = 0
theoremmagicRequestCount_compileWithToffoli_CCX
theorem magicRequestCount_compileWithToffoli_CCX
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) (a b c : Nat) :
    magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl (Gate.CCX a b c))
      = magicRequestCount (obl.ccx_program a b c)
theoremmagicRequestCount_compileWithToffoli_seq
theorem magicRequestCount_compileWithToffoli_seq
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) (g₁ g₂ : Gate) :
    magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl (Gate.seq g₁ g₂))
      = magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl g₁)
        + magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl g₂)
theoremmagicRequestCount_compileWithToffoli_ICX
theorem magicRequestCount_compileWithToffoli_ICX
    (F : TFactoryContract) (obl : TFactoryToffoliObligationV2 F) :
    ∀ g, isICXGate g = true →
      magicRequestCount (compileArithmeticGateToPPMWithToffoli F obl g) = 0

FormalRV.PPM.CircuitToPPMObservationBridge

FormalRV/PPM/CircuitToPPMObservationBridge.lean
FormalRV.Framework.CircuitToPPMObservationBridge — the honest Boolean-basis (computational-basis) PPM reference semantics that CLOSES the `PPMRefinesApplyNat` obligation for the ICX fragment without any external bridge, reflection, or magic assumption. ## E20 review finding (why a new model is needed) `LogicalPPMState` (in `CircuitToPPMInterface.lean`) carries `stabilizer : PPMOp.StabilizerState`, `frame : LogicalPauliFrame` (lists of qubits with deferred X/Z corrections), and `magicUsed : Nat`. None of these exposes a Boolean valuation `Nat → Bool` on logical qubits. Moreover, cxMacroGateRel n (Gate.CX c tgt) s u toggles the X-frame on `tgt` UNCONDITIONALLY (no dependence on the control's value). Boolean `Gate.CX` is CONTROLLED: target flips iff control bit is `1`. The cxMacro relation therefore does NOT match Boolean `Gate.CX` semantics, and a concrete `PPMRefinesApplyNat (cxMacroPPMSemanticsModel n)` instance cannot be honestly defined. Per the E18/E19/E20 honesty rule we do NOT fake an observation map on `LogicalPPMState`. Instead this file introduces a SEPARATE reference Boolean-basis model: basisPPMSemanticsModel : GateToPPMSemanticsModel whose `gateRel` matches `Gate.applyNat` exactly, and whose `ppmCommandRel` is the unique deterministic interpretation under which the existing compiler's ICX-fragment PPM expansion is sound. ## What this file proves `BasisPPMState` and `basisPPMSemanticsModel`. `basisRefinesApplyNat` — concrete `PPMRefinesApplyNat` instance with honest `encodeBits`/`observesBits`/ `gateRel_applyNat_obs`. `basisPPMSound_ICX` — ICX forward `ImplementsGateAsPPM`. `basisPPMReflects_ICX` — ICX `PPMReflectsGateRel`. `compileICXGateToPPM_applyNat_bridge_basisPPM` — ICX `LogicalGateAsPPMApplyNat` instance with NO external arguments (no `bridge`, no `hreflect`). `shor_arithmetic_ICX_correctness_transfers_to_basisPPM` — Shor-facing ICX decoder transfer with NO external arguments. ## Honesty boundary `basisPPMSemanticsModel` is a REFERENCE Boolean-basis semantics. It is NOT a claim that real lattice-surgery /stabilizer PPM physically realises CX via the `[measurePauliKind Z; applyFrameUpdate]` placeholder expansion. In real lattice surgery, a logical CNOT uses ancilla qubits + conditional Pauli corrections determined by measurement outcomes. Our basis `ppmCommandRel` is the deterministic interpretation that makes the existing placeholder compiler sound; it does NOT model measurement-outcome randomness or fault-tolerance. `cxMacroPPMSemanticsModel` and `basisPPMSemanticsModel` are NOT claimed equivalent or simulation-related. Any bridge between them is a separate future deliverable (it would need either an outcome-tracking observation map or a reformulation of `cxMacroGateRel` to encode control-dependence). CCX/Toffoli is NOT proved here. `basisPPMGateRel` does include a Boolean Toffoli case (matching `Gate.applyNat (Gate.CCX a b c)`), but the `useMagicT` command's interpretation is identity-on-bits + magic-count increment, which does NOT match Boolean Toffoli composed with `measurePauliKind Z` + `applyFrameUpdate`. CCX therefore remains an open obligation; we explicitly do NOT claim ICX coverage of CCX. QEC/surgery/backend lowering of ideal PPM remains open above this file. QPE / non-Clifford rotations remain out of scope (no rotation constructor in the arithmetic Gate IR).
structureBasisPPMState
structure BasisPPMState
A computational-basis PPM state: a Boolean bit-function plus the magic-state resource counter. No stabilizer or Pauli frame — this is a REFERENCE basis model, not a physical-substrate model.
instanceInhabited
instance : Inhabited BasisPPMState
defbasisPPMGateRel
def basisPPMGateRel : Gate → BasisPPMState → BasisPPMState → Prop
  | .I,         s, t => t = s
  | .X q,       s, t =>
      t.bits = update s.bits q (!s.bits q)
      ∧ t.magicUsed = s.magicUsed
  | .CX c tgt,  s, t =>
      t.bits = update s.bits tgt (xor (s.bits tgt) (s.bits c))
      ∧ t.magicUsed = s.magicUsed
  | .CCX a b c, s, t =>
      t.bits = update s.bits c (xor (s.bits c) (s.bits a && s.bits b))
      ∧ t.magicUsed = s.magicUsed + 1
  | .seq g₁ g₂, s, u =>
defbasisPPMCommandRel
def basisPPMCommandRel :
    PPMCommand → BasisPPMState → BasisPPMState → Prop
  | .applyFrameUpdate qs, s, t =>
      t.bits = qs.foldl (fun bs q => update bs q (!bs q)) s.bits
      ∧ t.magicUsed = s.magicUsed
  | .measurePauliKind PauliKind.Z [c, tgt], s, t =>
      t.bits = update s.bits tgt (xor (s.bits tgt) (!s.bits c))
      ∧ t.magicUsed = s.magicUsed
  | .measurePauliKind _ _, s, t =>
      t = s
  | .useMagicT _, s, t =>
      t.bits = s.bits
defbasisPPMSemanticsModel
def basisPPMSemanticsModel : GateToPPMSemanticsModel
defbasisEncodeBits
def basisEncodeBits (f : Nat → Bool) : basisPPMSemanticsModel.State
Encode a Boolean bit-state as a `BasisPPMState` with zero magic usage.
defbasisObservesBits
def basisObservesBits
    (s : basisPPMSemanticsModel.State) (f : Nat → Bool) : Prop
A `BasisPPMState` observes the bit-function it carries on its `bits` field.
theorembasisEncode_observes
theorem basisEncode_observes (f : Nat → Bool) :
    basisObservesBits (basisEncodeBits f) f
theorembasisPPMGateRel_imp_applyNat
theorem basisPPMGateRel_imp_applyNat
    (g : Gate) :
    ∀ (s σ' : BasisPPMState),
      basisPPMGateRel g s σ' → σ'.bits = Gate.applyNat g s.bits
Generalised statement: any `basisPPMGateRel` transition produces a target state whose `bits` field equals `Gate.applyNat g` applied to the source's bits.
theorembasisGateRel_applyNat_obs
theorem basisGateRel_applyNat_obs
    (g : Gate) (f : Nat → Bool) (σ' : basisPPMSemanticsModel.State)
    (h : basisPPMSemanticsModel.gateRel g (basisEncodeBits f) σ') :
    basisObservesBits σ' (Gate.applyNat g f)
The bridge field for `PPMRefinesApplyNat`.
defbasisRefinesApplyNat
def basisRefinesApplyNat : PPMRefinesApplyNat basisPPMSemanticsModel
theorembasisPPM_I_sound
theorem basisPPM_I_sound :
    ImplementsGateAsPPM basisPPMSemanticsModel Gate.I
      (compileArithmeticGateToPPM Gate.I)
theorembasisPPM_X_sound
theorem basisPPM_X_sound (q : Nat) :
    ImplementsGateAsPPM basisPPMSemanticsModel (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
theorembasisPPM_CX_sound
theorem basisPPM_CX_sound (c tgt : Nat) :
    ImplementsGateAsPPM basisPPMSemanticsModel (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
theorembasisPPM_seq_sound
theorem basisPPM_seq_sound (g₁ g₂ : Gate)
    (h₁ : ImplementsGateAsPPM basisPPMSemanticsModel g₁
            (compileArithmeticGateToPPM g₁))
    (h₂ : ImplementsGateAsPPM basisPPMSemanticsModel g₂
            (compileArithmeticGateToPPM g₂)) :
    ImplementsGateAsPPM basisPPMSemanticsModel (Gate.seq g₁ g₂)
      (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
theorembasisPPMSound_ICX
theorem basisPPMSound_ICX :
    ∀ g, isICXGate g = true →
      ImplementsGateAsPPM basisPPMSemanticsModel g
        (compileArithmeticGateToPPM g)
theorembasisPPM_I_reflects
theorem basisPPM_I_reflects :
    PPMReflectsGateRel basisPPMSemanticsModel Gate.I
      (compileArithmeticGateToPPM Gate.I)
theorembasisPPM_X_reflects
theorem basisPPM_X_reflects (q : Nat) :
    PPMReflectsGateRel basisPPMSemanticsModel (Gate.X q)
      (compileArithmeticGateToPPM (Gate.X q))
theorembasisPPM_CX_reflects
theorem basisPPM_CX_reflects (c tgt : Nat) :
    PPMReflectsGateRel basisPPMSemanticsModel (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
theorembasisPPM_seq_reflects
theorem basisPPM_seq_reflects (g₁ g₂ : Gate)
    (h₁ : PPMReflectsGateRel basisPPMSemanticsModel g₁
            (compileArithmeticGateToPPM g₁))
    (h₂ : PPMReflectsGateRel basisPPMSemanticsModel g₂
            (compileArithmeticGateToPPM g₂)) :
    PPMReflectsGateRel basisPPMSemanticsModel (Gate.seq g₁ g₂)
      (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
theorembasisPPMReflects_ICX
theorem basisPPMReflects_ICX :
    ∀ g, isICXGate g = true →
      PPMReflectsGateRel basisPPMSemanticsModel g
        (compileArithmeticGateToPPM g)
theoremcompileICXGateToPPM_applyNat_bridge_basisPPM
theorem compileICXGateToPPM_applyNat_bridge_basisPPM
    (g : Gate) (hICX : isICXGate g = true) :
    LogicalGateAsPPMApplyNat basisPPMSemanticsModel
      basisRefinesApplyNat g
theoremshor_arithmetic_ICX_correctness_transfers_to_basisPPM
theorem shor_arithmetic_ICX_correctness_transfers_to_basisPPM
    (g : Gate) (hICX : isICXGate g = true)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (σ' : basisPPMSemanticsModel.State)
    (hrun :
      PPMProgramRel basisPPMSemanticsModel
        (compileArithmeticGateToPPM g)
        (basisRefinesApplyNat.encodeBits input)
        σ')
    (hGateCorrect :
      decode (Gate.applyNat g input) = expected) :

FormalRV.PPM.CircuitToPPMResource

FormalRV/PPM/CircuitToPPMResource.lean
FormalRV.PPM.CircuitToPPMResource — GENERIC gate-by-gate PPM compilation and the proved WHOLE-CIRCUIT resource formula. Any higher-level circuit (any Shor implementation, expressed as a `List HLGate`) is compiled gate by gate to a concrete PPM program (`circuitToPPM`), and every resource count of the assembled program is proved EQUAL to the sum of per-gate costs (`*_circuitToPPM`). So: the framework works for ANY circuit / any Shor variant — it is parametric in the gate list `gs`; the full Shor→Clifford+T→PPM program is assembled gate by gate on demand (`circuitToPPM na gs`); a CONCRETE circuit yields a PROVED literal resource number (the sum, closed by `decide`/`native_decide`). Clifford gates compile to themselves (frame-tracked / "free"); T and CCZ consume a magic state via the teleportation gadgets of `PPMToQASM` (matching `GadgetChannel`). No `sorry`, no new `axiom`.
inductiveHLGate
inductive HLGate
defgateToPPM
def gateToPPM (na : Nat) : HLGate → List QasmOp
  | .H q       => [.opH q]
  | .S q       => [.opS q]
  | .X q       => [.opX q]
  | .Z q       => [.opZ q]
  | .CNOT c t  => [.opCX c t]
  | .T q       => [.opH na, .opT na, .opCX q na, .opMeas na 0, .opIf 0 (.opS q)]
  | .CCZ a b c =>
      [ .opH na, .opH (na+1), .opH (na+2), .opCCZ na (na+1) (na+2),
        .opCX a na, .opCX b (na+1), .opCX c (na+2),
        .opMeas na 0, .opMeas (na+1) 1, .opMeas (na+2) 2,
        .opIf 0 (.opCZ b c), .opIf 1 (.opCZ a c), .opIf 2 (.opCZ a b),
defcircuitToPPM
def circuitToPPM (na : Nat) (gs : List HLGate) : List QasmOp
The whole compiled PPM program: each gate's gadget, concatenated.
defgateTMagic
def gateTMagic : HLGate → Nat | .T _ => 1 | _ => 0
defgateCCZMagic
def gateCCZMagic : HLGate → Nat | .CCZ _ _ _ => 1 | _ => 0
defgateMeas
def gateMeas : HLGate → Nat | .T _ => 1 | .CCZ _ _ _ => 3 | _ => 0
defgateClifford
def gateClifford : HLGate → Nat
  | .H _ => 1 | .S _ => 1 | .X _ => 1 | .Z _ => 1 | .CNOT _ _ => 1
  | .T _ => 2 | .CCZ _ _ _ => 6
defgateFeedforward
def gateFeedforward : HLGate → Nat | .T _ => 1 | .CCZ _ _ _ => 6 | _ => 0
theoremnumTMagic_gateToPPM
theorem numTMagic_gateToPPM (na : Nat) (g : HLGate) :
    numTMagic (gateToPPM na g) = gateTMagic g
Per-gate gadget counts agree with the per-gate cost functions (by cases).
theoremnumCCZMagic_gateToPPM
theorem numCCZMagic_gateToPPM (na : Nat) (g : HLGate) :
    numCCZMagic (gateToPPM na g) = gateCCZMagic g
theoremnumMeas_gateToPPM
theorem numMeas_gateToPPM (na : Nat) (g : HLGate) :
    numMeas (gateToPPM na g) = gateMeas g
theoremnumClifford_gateToPPM
theorem numClifford_gateToPPM (na : Nat) (g : HLGate) :
    numClifford (gateToPPM na g) = gateClifford g
theoremnumFeedforward_gateToPPM
theorem numFeedforward_gateToPPM (na : Nat) (g : HLGate) :
    numFeedforward (gateToPPM na g) = gateFeedforward g
theoremnumTMagic_circuitToPPM
theorem numTMagic_circuitToPPM (na : Nat) (gs : List HLGate) :
    numTMagic (circuitToPPM na gs) = (gs.map gateTMagic).sum
theoremnumCCZMagic_circuitToPPM
theorem numCCZMagic_circuitToPPM (na : Nat) (gs : List HLGate) :
    numCCZMagic (circuitToPPM na gs) = (gs.map gateCCZMagic).sum
theoremnumMeas_circuitToPPM
theorem numMeas_circuitToPPM (na : Nat) (gs : List HLGate) :
    numMeas (circuitToPPM na gs) = (gs.map gateMeas).sum
theoremnumClifford_circuitToPPM
theorem numClifford_circuitToPPM (na : Nat) (gs : List HLGate) :
    numClifford (circuitToPPM na gs) = (gs.map gateClifford).sum
theoremnumFeedforward_circuitToPPM
theorem numFeedforward_circuitToPPM (na : Nat) (gs : List HLGate) :
    numFeedforward (circuitToPPM na gs) = (gs.map gateFeedforward).sum
defdemoCircuit
def demoCircuit : List HLGate
theoremdemo_TMagic
theorem demo_TMagic   : numTMagic   (circuitToPPM 3 demoCircuit) = 2
theoremdemo_CCZMagic
theorem demo_CCZMagic : numCCZMagic (circuitToPPM 3 demoCircuit) = 1
theoremdemo_Meas
theorem demo_Meas     : numMeas     (circuitToPPM 3 demoCircuit) = 5
theoremdemo_Clifford
theorem demo_Clifford : numClifford (circuitToPPM 3 demoCircuit) = 12
theoremdemo_Feedforward
theorem demo_Feedforward : numFeedforward (circuitToPPM 3 demoCircuit) = 8
deftoffoli
def toffoli (a b c : Nat) : List HLGate
A Toffoli as `H·CCZ·H` in the high-level gate set.
defshor15Modmult
def shor15Modmult : List HLGate
The Shor-15 (a = 7) modular multiplier: 27 Toffolis + 12 CNOTs.
theoremshor15_TMagic
theorem shor15_TMagic      : numTMagic      (circuitToPPM 8 shor15Modmult) = 0
theoremshor15_CCZMagic
theorem shor15_CCZMagic    : numCCZMagic    (circuitToPPM 8 shor15Modmult) = 27
theoremshor15_Meas
theorem shor15_Meas        : numMeas        (circuitToPPM 8 shor15Modmult) = 81
27 CCZ gadgets × 3 Z-basis syndrome measurements = 81 Pauli measurements, matching the Qiskit count exactly.
theoremshor15_Clifford
theorem shor15_Clifford    : numClifford    (circuitToPPM 8 shor15Modmult) = 228
theoremshor15_Feedforward
theorem shor15_Feedforward : numFeedforward (circuitToPPM 8 shor15Modmult) = 162
theoremsum_map_flatten_replicate
theorem sum_map_flatten_replicate (n : Nat) (L : List HLGate) (f : HLGate → Nat) :
    (((List.replicate n L).flatten).map f).sum = n * (L.map f).sum
Helper: sum of `f` over `n` concatenated copies of a block `L` is `n · (sum over L)`.
defmodmultBlock
def modmultBlock (nToff nCnot : Nat) : List HLGate
A generic modular-multiplier block: `nToff` Toffolis (each `H·CCZ·H`) + `nCnot` CNOTs.
theoremmodmult_CCZMagic
theorem modmult_CCZMagic (nToff nCnot : Nat) :
    numCCZMagic (circuitToPPM 8 (modmultBlock nToff nCnot)) = nToff
Magic states scale exactly with the Toffoli count — for ANY size.
theoremmodmult_Meas
theorem modmult_Meas (nToff nCnot : Nat) :
    numMeas (circuitToPPM 8 (modmultBlock nToff nCnot)) = 3 * nToff
Pauli measurements scale as `3·(Toffoli count)` — for ANY size.
example(example)
example : numCCZMagic (circuitToPPM 8 (modmultBlock 27 12)) = 27
Sanity: the parametric formula reproduces the proved Shor-15 totals at `nToff = 27`.
example(example)
example : numMeas (circuitToPPM 8 (modmultBlock 27 12)) = 81

FormalRV.PPM.CircuitToPPMSemanticBridge

FormalRV/PPM/CircuitToPPMSemanticBridge.lean
FormalRV.Framework.CircuitToPPMSemanticBridge — the semantic-refinement bridge from compiled ideal PPM programs to `Gate.applyNat`-level Boolean-function correctness, which is the semantic layer Shor's arithmetic stack uses. ## What this file IS A minimal, honest, parametric refinement interface stating: PPM-program execution starting from an `encodeBits f` state observationally refines `Gate.applyNat g f`. Combined with existing `Gate.applyNat`-level arithmetic correctness theorems (e.g., `cuccaro_target_val_eq_...` in `FormalRV.BQAlgo.CuccaroDecoded`), this lets us TRANSFER decoder-level postconditions from the logical-Gate layer down to the compiled ideal-PPM layer, without faking any quantum semantics. Concretely, the file provides: `PPMRefinesApplyNat sem` — a parametric bridge interface pairing an encoding `(Nat → Bool) → State`, an observation relation `State → (Nat → Bool) → Prop`, and the per-gate refinement field `gateRel_applyNat_obs`. `PPMReflectsGateRel sem g ppm` — the converse direction of `ImplementsGateAsPPM`, exposed honestly as a separate interface field (since `ImplementsGateAsPPM` alone is forward-only and cannot derive `applyNatSound`). `LogicalGateAsPPMApplyNat sem bridge g` — the per-gate refinement predicate combining `ppmSound` (`ImplementsGateAsPPM`) and `applyNatSound` (the direction we actually need to transfer postconditions). `LogicalGateAsPPMApplyNat.from_refinement` — the generic constructor. `compileICXGateToPPM_applyNat_bridge` — instance for the ICX fragment using the existing `cxMacroPPMSemanticsModel` + `compileICXGateToPPM_sound_from_cxMacro`. `compileArithmeticGateToPPM_applyNat_bridge_from_magic` — instance for the FULL arithmetic fragment (including CCX) via `compileArithmeticGateToPPM_sound_from_magic_interface`, modulo the existing `MagicInjectionObligations.CCX_ok`. `applyNat_postcondition_transfers_to_PPM` — abstract `(Nat → Bool) → Prop` transfer theorem. `decoder_postcondition_transfers_to_PPM` — decoder-shaped specialisation (`decode (Gate.applyNat g input) = expected`). `shor_arithmetic_applyNat_correctness_transfers_to_PPM` — Shor-facing wrapper at arithmetic-block level. ## What this file is NOT This file does NOT prove: QEC / lattice-surgery / backend SysCall schedules implement ideal PPM measurement (still open above the PPM layer). Decoder correctness (the syndrome decoder is not modelled semantically anywhere in the project). Syndrome correctness. Code distance. Fault tolerance. CCX / Toffoli magic injection (only EXPOSED as an explicit `MagicInjectionObligations.CCX_ok` assumption; never discharged here). QPE arbitrary / non-Clifford rotations (the arithmetic Gate IR has no rotation constructor). Full Shor success-probability correctness. Any concrete `PPMRefinesApplyNat` instance for `cxMacroPPMSemanticsModel n` (the bridge is parametric; we deliberately do NOT define a fake `encodeBits` / `observesBits` pair). The deliverable is the abstract refinement interface plus the transfer theorems. Concrete model instances become a separate future tick whose only honest discharge requires a real semantic state model.
structurePPMRefinesApplyNat
structure PPMRefinesApplyNat (sem : GateToPPMSemanticsModel)
Parametric semantic refinement bridge between an abstract `GateToPPMSemanticsModel` and the canonical Boolean-function Gate semantics `Gate.applyNat`.
defPPMReflectsGateRel
def PPMReflectsGateRel
    (sem : GateToPPMSemanticsModel)
    (g : Gate) (ppm : PPMProgram) : Prop
Converse of `ImplementsGateAsPPM`: every PPM-program transition factors through the gate's semantic relation. Honestly named so consumers see the asymmetry.
structureLogicalGateAsPPMApplyNat
structure LogicalGateAsPPMApplyNat
    (sem : GateToPPMSemanticsModel)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate) : Prop
A `Gate` `g` is refined by its compiled PPM program in the sense Shor's arithmetic stack needs: `ppmSound` — forward `ImplementsGateAsPPM`; `applyNatSound` — every PPM-program execution from an encoded bit-input lands in a state observing the `Gate.applyNat g` image.
theoremLogicalGateAsPPMApplyNat.from_refinement
theorem LogicalGateAsPPMApplyNat.from_refinement
    (sem : GateToPPMSemanticsModel)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (hppm :
      ImplementsGateAsPPM sem g (compileArithmeticGateToPPM g))
    (hreflect :
      PPMReflectsGateRel sem g (compileArithmeticGateToPPM g)) :
    LogicalGateAsPPMApplyNat sem bridge g
theoremcompileICXGateToPPM_applyNat_bridge
theorem compileICXGateToPPM_applyNat_bridge
    (n : Nat)
    (bridge : PPMRefinesApplyNat (cxMacroPPMSemanticsModel n))
    (g : Gate)
    (hICX : isICXGate g = true)
    (hreflect :
      PPMReflectsGateRel (cxMacroPPMSemanticsModel n) g
        (compileArithmeticGateToPPM g)) :
    LogicalGateAsPPMApplyNat (cxMacroPPMSemanticsModel n) bridge g
theoremPPMProgramRel_nil_iff
theorem PPMProgramRel_nil_iff
    (sem : GateToPPMSemanticsModel) (s t : sem.State) :
    PPMProgramRel sem [] s t ↔ s = t
Empty-program inversion: `PPMProgramRel sem [] s t` iff `s = t`.
theoremPPMProgramRel_cons_inv
theorem PPMProgramRel_cons_inv
    (sem : GateToPPMSemanticsModel)
    (cmd : PPMCommand) (rest : PPMProgram)
    (s u : sem.State)
    (h : PPMProgramRel sem (cmd :: rest) s u) :
    ∃ mid, sem.ppmCommandRel cmd s mid
        ∧ PPMProgramRel sem rest mid u
Cons-program inversion: every `cmd :: rest` execution factors through an intermediate state reached by `cmd`.
theoremPPMProgramRel_append_inv
theorem PPMProgramRel_append_inv
    (sem : GateToPPMSemanticsModel)
    (p q : PPMProgram) (s u : sem.State)
    (h : PPMProgramRel sem (p ++ q) s u) :
    ∃ mid, PPMProgramRel sem p s mid
        ∧ PPMProgramRel sem q mid u
Append-program inversion (forward direction of the existing iff `PPMProgramRel_append`). Restated as a one-arrow form for convenience.
theoremcxMacro_I_reflects_gateRel
theorem cxMacro_I_reflects_gateRel (n : Nat) :
    PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
      Gate.I (compileArithmeticGateToPPM Gate.I)
`Gate.I` reflects: the empty compiled program forces `s = t`, which is exactly `cxMacroGateRel n Gate.I`.
theoremcxMacro_X_reflects_gateRel
theorem cxMacro_X_reflects_gateRel (n : Nat) (q : Nat) :
    PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
      (Gate.X q) (compileArithmeticGateToPPM (Gate.X q))
`Gate.X q` reflects: the singleton `applyFrameUpdate [q]` program forces the macro X-frame toggle. `q : Nat` is the logical-qubit index.
theoremcxMacro_CX_reflects_gateRel
theorem cxMacro_CX_reflects_gateRel
    (n : Nat) (c tgt : Nat) :
    PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
      (Gate.CX c tgt)
      (compileArithmeticGateToPPM (Gate.CX c tgt))
`Gate.CX c tgt` reflects. Inverts the two-command program `[measurePauliKind Z [c, tgt], applyFrameUpdate [tgt]]` step by step and recovers the existential Gottesman-branch witness baked into `cxMacroGateRel`.
theoremcxMacro_seq_reflects_gateRel
theorem cxMacro_seq_reflects_gateRel
    (n : Nat) (g₁ g₂ : Gate)
    (h₁ :
      PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
        g₁ (compileArithmeticGateToPPM g₁))
    (h₂ :
      PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
        g₂ (compileArithmeticGateToPPM g₂)) :
    PPMReflectsGateRel (cxMacroPPMSemanticsModel n)
      (Gate.seq g₁ g₂)
      (compileArithmeticGateToPPM (Gate.seq g₁ g₂))
`Gate.seq g₁ g₂` reflects whenever both components reflect. Inverts the appended compiled program via `PPMProgramRel_append_inv`.
theoremcompileICXGateToPPM_reflects_gateRel_from_cxMacro
theorem compileICXGateToPPM_reflects_gateRel_from_cxMacro
    (n : Nat) :
    ∀ g, isICXGate g = true →
      PPMReflectsGateRel (cxMacroPPMSemanticsModel n) g
        (compileArithmeticGateToPPM g)
For every Gate `g` in the ICX fragment (no CCX), the compiled PPM program reflects back to `cxMacroGateRel n`. Proven by induction on `g` matching the §16.e forward soundness proof's case split.
theoremcompileICXGateToPPM_applyNat_bridge_no_reflect_hyp
theorem compileICXGateToPPM_applyNat_bridge_no_reflect_hyp
    (n : Nat)
    (bridge : PPMRefinesApplyNat (cxMacroPPMSemanticsModel n))
    (g : Gate)
    (hICX : isICXGate g = true) :
    LogicalGateAsPPMApplyNat (cxMacroPPMSemanticsModel n) bridge g
theoremapplyNat_postcondition_transfers_to_PPM
theorem applyNat_postcondition_transfers_to_PPM
    (sem : GateToPPMSemanticsModel)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (P : (Nat → Bool) → Prop)
    (hbridge : LogicalGateAsPPMApplyNat sem bridge g)
    (input : Nat → Bool)
    (σ' : sem.State)
    (hrun :
      PPMProgramRel sem
        (compileArithmeticGateToPPM g)
        (bridge.encodeBits input)
Any predicate `P` over output bit-states that holds for `Gate.applyNat g input` also holds for some bit-state observed by the PPM-program output state. This is the abstract semantic transport from `Gate.applyNat`-level correctness to PPM-program execution.
theoremdecoder_postcondition_transfers_to_PPM
theorem decoder_postcondition_transfers_to_PPM
    (sem : GateToPPMSemanticsModel)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (decode : (Nat → Bool) → Nat)
    (expected : Nat)
    (hbridge : LogicalGateAsPPMApplyNat sem bridge g)
    (input : Nat → Bool)
    (σ' : sem.State)
    (hrun :
      PPMProgramRel sem
        (compileArithmeticGateToPPM g)
theoremshor_arithmetic_applyNat_correctness_transfers_to_PPM
theorem shor_arithmetic_applyNat_correctness_transfers_to_PPM
    (sem : GateToPPMSemanticsModel)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool)
    (expected : Nat)
    (hbridge : LogicalGateAsPPMApplyNat sem bridge g)
    (σ' : sem.State)
    (hrun :
      PPMProgramRel sem
        (compileArithmeticGateToPPM g)
theoremshor_arithmetic_ICX_correctness_transfers_to_PPM_no_reflect_hyp
theorem shor_arithmetic_ICX_correctness_transfers_to_PPM_no_reflect_hyp
    (n : Nat)
    (bridge : PPMRefinesApplyNat (cxMacroPPMSemanticsModel n))
    (g : Gate)
    (hICX : isICXGate g = true)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool)
    (expected : Nat)
    (σ' : (cxMacroPPMSemanticsModel n).State)
    (hrun :
      PPMProgramRel (cxMacroPPMSemanticsModel n)
        (compileArithmeticGateToPPM g)
theoremcompileArithmeticGateToPPM_applyNat_bridge_from_magic
theorem compileArithmeticGateToPPM_applyNat_bridge_from_magic
    (sem : GateToPPMSemanticsModel)
    (icx : ArithmeticICXPrimitivePPMObligations sem)
    (mag : MagicInjectionObligations sem)
    (hseq :
      ∀ g₁ g₂ s u,
        sem.gateRel (Gate.seq g₁ g₂) s u ↔
          ∃ t, sem.gateRel g₁ s t ∧ sem.gateRel g₂ t u)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (hreflect :
      PPMReflectsGateRel sem g (compileArithmeticGateToPPM g)) :
theoremshor_arithmetic_full_correctness_transfers_to_PPM_modulo_magic
theorem shor_arithmetic_full_correctness_transfers_to_PPM_modulo_magic
    (sem : GateToPPMSemanticsModel)
    (icx : ArithmeticICXPrimitivePPMObligations sem)
    (mag : MagicInjectionObligations sem)
    (hseq :
      ∀ g₁ g₂ s u,
        sem.gateRel (Gate.seq g₁ g₂) s u ↔
          ∃ t, sem.gateRel g₁ s t ∧ sem.gateRel g₂ t u)
    (bridge : PPMRefinesApplyNat sem)
    (g : Gate)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool)

FormalRV.PPM.CircuitToPPMToffoliMagic

FormalRV/PPM/CircuitToPPMToffoliMagic.lean
FormalRV.Framework.CircuitToPPMToffoliMagic — PPM-level Toffoli teleportation primitive + extended command IR. ## E22 review and motivation E22 introduced `TFactoryToffoliObligationV2`, the non-vacuous Toffoli obligation, but did NOT instantiate it. The reason: the existing `PPMCommand` IR exposes three commands — `applyFrameUpdate qs` (deterministic bit flip), `measurePauliKind pk qs` (in `basisPPMCommandRel`, identity except for the special `Z [c, t]` case which writes a CX-style XOR-with-NOT bit), `useMagicT q` (resource counter; no nonlinear semantics in `magicBasisPPMCommandRel`). None of these can construct nonlinear Boolean Toffoli on the success branch without conditional / nonlinear control by the bit values — which the existing `magicBasisPPMCommandRel` does not provide. ## What this file adds This file introduces an EXTENDED command IR `MagicPPMCommand` with two cases: `base : PPMCommand → MagicPPMCommand` `teleportCCX : Nat → Nat → Nat → MagicPPMCommand` and the matching `MagicPPMProgram := List MagicPPMCommand`, `MagicPPMProgramRel F`, and a new compiler `compileArithmeticGateToMagicPPM`. The `teleportCCX a b c` primitive's relation `teleportCCXRel F a b c s t` says: there exists a certified-T token at the head of the magic pool that the primitive consumes, and `t.bits = Gate.applyNat (Gate.CCX a b c) s.bits`. This is the SUCCESS-BRANCH semantics of an abstract gate-teleportation contract. Using this primitive, we instantiate a non-vacuous `TFactoryToffoliObligationV3` and prove a full-arithmetic Shor decoder transfer through the extended compiler WITHOUT requiring an external Toffoli obligation argument. ## Honesty boundary This file does NOT prove: Physical factory / distillation correctness. The internal Clifford+T circuit that realises gate-teleportation Toffoli; `teleportCCXRel` is the success-branch CONTRACT, not its low-level proof. QEC / backend implementation of the factory or of teleportation. Full Shor success-probability correctness. QPE / non-Clifford rotations. Any equivalence between `MagicPPMProgram` and a backend SysCall schedule. The PPM-level teleportation primitive is honest at THIS layer: it abstracts the internal teleportation circuit into one named relation whose obligations (certified token consumption + Boolean Toffoli output) are explicit. A future tick can refine `teleportCCXRel` into a Clifford+T circuit proof.
inductiveMagicPPMCommand
inductive MagicPPMCommand : Type
  | base        : PPMCommand → MagicPPMCommand
  | teleportCCX : Nat → Nat → Nat → MagicPPMCommand
  deriving Inhabited
abbrevMagicPPMProgram
abbrev MagicPPMProgram
defmagicPPMCommandMagicTCount
def magicPPMCommandMagicTCount : MagicPPMCommand → Nat
  | .base cmd          => ppmCommandMagicTCount cmd
  | .teleportCCX _ _ _ => 1
defmagicPPMRequestCount
def magicPPMRequestCount (p : MagicPPMProgram) : Nat
theoremmagicPPMRequestCount_nil
theorem magicPPMRequestCount_nil :
    magicPPMRequestCount [] = 0
theoremmagicPPMRequestCount_append
theorem magicPPMRequestCount_append (p q : MagicPPMProgram) :
    magicPPMRequestCount (p ++ q)
      = magicPPMRequestCount p + magicPPMRequestCount q
theoremmagicPPMRequestCount_teleportCCX
theorem magicPPMRequestCount_teleportCCX (a b c : Nat) :
    magicPPMRequestCount [MagicPPMCommand.teleportCCX a b c] = 1
defteleportCCXRel
def teleportCCXRel
    (F : TFactoryContract) (a b c : Nat)
    (s t : MagicBasisPPMState) : Prop
The success-branch relation for the abstract Toffoli teleportation primitive. Consumes one certified-T token from the head of the pool and writes the Boolean Toffoli output on `bits`.
defmagicPPMCommandRel
def magicPPMCommandRel
    (F : TFactoryContract) :
    MagicPPMCommand → MagicBasisPPMState → MagicBasisPPMState → Prop
  | .base cmd,          s, t => magicBasisPPMCommandRel F cmd s t
  | .teleportCCX a b c, s, t => teleportCCXRel F a b c s t
The extended command relation. `.base cmd` dispatches to `magicBasisPPMCommandRel F`. `.teleportCCX a b c` invokes `teleportCCXRel`.
inductiveMagicPPMProgramRel
inductive MagicPPMProgramRel (F : TFactoryContract) :
    MagicPPMProgram → MagicBasisPPMState → MagicBasisPPMState → Prop
  | nil  (s : MagicBasisPPMState) : MagicPPMProgramRel F [] s s
  | cons {cmd : MagicPPMCommand} {rest : MagicPPMProgram}
         {s t u : MagicBasisPPMState}
         (h1 : magicPPMCommandRel F cmd s t)
         (h2 : MagicPPMProgramRel F rest t u) :
         MagicPPMProgramRel F (cmd :: rest) s u
theoremMagicPPMProgramRel_nil_iff
theorem MagicPPMProgramRel_nil_iff
    (F : TFactoryContract) (s t : MagicBasisPPMState) :
    MagicPPMProgramRel F [] s t ↔ s = t
theoremMagicPPMProgramRel_cons_inv
theorem MagicPPMProgramRel_cons_inv
    (F : TFactoryContract)
    (cmd : MagicPPMCommand) (rest : MagicPPMProgram)
    (s u : MagicBasisPPMState)
    (h : MagicPPMProgramRel F (cmd :: rest) s u) :
    ∃ mid, magicPPMCommandRel F cmd s mid
        ∧ MagicPPMProgramRel F rest mid u
theoremMagicPPMProgramRel_append
theorem MagicPPMProgramRel_append
    (F : TFactoryContract) (p q : MagicPPMProgram)
    (s u : MagicBasisPPMState) :
    MagicPPMProgramRel F (p ++ q) s u ↔
      ∃ t, MagicPPMProgramRel F p s t ∧ MagicPPMProgramRel F q t u
theoremMagicPPMProgramRel_append_inv
theorem MagicPPMProgramRel_append_inv
    (F : TFactoryContract) (p q : MagicPPMProgram)
    (s u : MagicBasisPPMState)
    (h : MagicPPMProgramRel F (p ++ q) s u) :
    ∃ mid, MagicPPMProgramRel F p s mid
        ∧ MagicPPMProgramRel F q mid u
theoremMagicPPMProgramRel_base_map_iff
theorem MagicPPMProgramRel_base_map_iff
    (F : TFactoryContract) (l : PPMProgram) :
    ∀ (s σ' : MagicBasisPPMState),
      MagicPPMProgramRel F (l.map MagicPPMCommand.base) s σ' ↔
        PPMProgramRel (magicBasisPPMSemanticsModel F) l s σ'
defteleportCCXProgram
def teleportCCXProgram (a b c : Nat) : MagicPPMProgram
theoremteleportCCXProgram_uses_magic
theorem teleportCCXProgram_uses_magic
    (F : TFactoryContract) (a b c : Nat) :
    magicPPMRequestCount (teleportCCXProgram a b c) > 0
theoremteleportCCXProgram_correct_on_success
theorem teleportCCXProgram_correct_on_success
    (F : TFactoryContract) (a b c : Nat)
    (input : Nat → Bool)
    (s σ' : MagicBasisPPMState)
    (hobs : (magicBasisRefinesApplyNat F).observesBits s input)
    (hrun : MagicPPMProgramRel F (teleportCCXProgram a b c) s σ') :
    (magicBasisRefinesApplyNat F).observesBits σ'
      (Gate.applyNat (Gate.CCX a b c) input)
defcompileArithmeticGateToMagicPPM
def compileArithmeticGateToMagicPPM : Gate → MagicPPMProgram
  | Gate.I         =>
      (compileArithmeticGateToPPM Gate.I).map MagicPPMCommand.base
  | Gate.X q       =>
      (compileArithmeticGateToPPM (Gate.X q)).map MagicPPMCommand.base
  | Gate.CX c t    =>
      (compileArithmeticGateToPPM (Gate.CX c t)).map MagicPPMCommand.base
  | Gate.CCX a b c => teleportCCXProgram a b c
  | Gate.seq g₁ g₂ =>
      compileArithmeticGateToMagicPPM g₁
        ++ compileArithmeticGateToMagicPPM g₂
theoremmagicBasisPPM_applyNat_sound_ICX_from_observed
theorem magicBasisPPM_applyNat_sound_ICX_from_observed
    (F : TFactoryContract)
    (g : Gate) (hICX : isICXGate g = true)
    (input : Nat → Bool)
    (s σ' : MagicBasisPPMState)
    (hobs : (magicBasisRefinesApplyNat F).observesBits s input)
    (hrun : PPMProgramRel (magicBasisPPMSemanticsModel F)
              (compileArithmeticGateToPPM g) s σ') :
    (magicBasisRefinesApplyNat F).observesBits σ'
      (Gate.applyNat g input)
theoremcompileArithmeticGateToMagicPPM_applyNat_sound_from_observed
theorem compileArithmeticGateToMagicPPM_applyNat_sound_from_observed
    (F : TFactoryContract) :
    ∀ (g : Gate) (input : Nat → Bool)
      (s σ' : MagicBasisPPMState),
      (magicBasisRefinesApplyNat F).observesBits s input →
      MagicPPMProgramRel F (compileArithmeticGateToMagicPPM g) s σ' →
      (magicBasisRefinesApplyNat F).observesBits σ'
        (Gate.applyNat g input)
theoremcompileArithmeticGateToMagicPPM_applyNat_sound
theorem compileArithmeticGateToMagicPPM_applyNat_sound
    (F : TFactoryContract)
    (g : Gate) (input : Nat → Bool)
    (σ' : MagicBasisPPMState)
    (hrun : MagicPPMProgramRel F
              (compileArithmeticGateToMagicPPM g)
              ((magicBasisRefinesApplyNat F).encodeBits input) σ') :
    (magicBasisRefinesApplyNat F).observesBits σ'
      (Gate.applyNat g input)
theoremshor_arithmetic_full_correctness_transfers_to_magicTeleportPPM
theorem shor_arithmetic_full_correctness_transfers_to_magicTeleportPPM
    (F : TFactoryContract)
    (g : Gate)
    (decode : (Nat → Bool) → Nat)
    (input : Nat → Bool) (expected : Nat)
    (σ' : MagicBasisPPMState)
    (hrun : MagicPPMProgramRel F
              (compileArithmeticGateToMagicPPM g)
              ((magicBasisRefinesApplyNat F).encodeBits input) σ')
    (hGateCorrect : decode (Gate.applyNat g input) = expected) :
    ∃ output,
      (magicBasisRefinesApplyNat F).observesBits σ' output
structureTFactoryToffoliObligationV3
structure TFactoryToffoliObligationV3 (F : TFactoryContract)
defteleportCCX_ToffoliObligationV3
def teleportCCX_ToffoliObligationV3 (F : TFactoryContract) :
    TFactoryToffoliObligationV3 F
Concrete instantiation of V3 using the explicit `teleportCCXProgram` primitive.
theoremmagicPPMRequestCount_base_map
theorem magicPPMRequestCount_base_map (l : PPMProgram) :
    magicPPMRequestCount (l.map MagicPPMCommand.base)
      = magicRequestCount l
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_I
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_I :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM Gate.I) = 0
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_X
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_X (q : Nat) :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM (Gate.X q)) = 0
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_CX
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_CX (c t : Nat) :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM (Gate.CX c t)) = 0
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_CCX
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_CCX (a b c : Nat) :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM (Gate.CCX a b c)) = 1
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_CCX_pos
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_CCX_pos
    (a b c : Nat) :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM (Gate.CCX a b c)) > 0
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_seq
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_seq (g₁ g₂ : Gate) :
    magicPPMRequestCount (compileArithmeticGateToMagicPPM (Gate.seq g₁ g₂))
      = magicPPMRequestCount (compileArithmeticGateToMagicPPM g₁)
        + magicPPMRequestCount (compileArithmeticGateToMagicPPM g₂)
theoremmagicPPMRequestCount_compileArithmeticGateToMagicPPM_ICX
theorem magicPPMRequestCount_compileArithmeticGateToMagicPPM_ICX :
    ∀ g, isICXGate g = true →
      magicPPMRequestCount (compileArithmeticGateToMagicPPM g) = 0

FormalRV.PPM.CliffordConj

FormalRV/PPM/CliffordConj.lean
FormalRV.Framework.CliffordConj — the GATE-LEVEL rung of the QEC verification stack. ## What this file is The physical realization of a single stabilizer measurement (a Pauli-Product Measurement, PPM) is a *gate* circuit: prepare ancilla `a` in |0⟩ (stabilized by Z_a) apply CNOT(data_i → a) for each i in the stabilizer support measure Z_a This file proves — from the single-qubit CNOT conjugation rules, by `decide` on the symplectic (x,z)-bit table — that this gate circuit measures exactly the intended stabilizer. ## The Heisenberg (Gottesman) picture A Clifford gate `C` conjugates a Pauli `P ↦ C P C†`. Measuring an observable `M` *after* `C` is the same as measuring `C† M C` before* `C`. So to find what the final `measure Z_a` measures on the input data, we conjugate the ancilla observable `Z_a` back through the gadget's CNOTs. For a Z-type stabilizer `S = ∏_{i∈supp} Z_i`, conjugating `Z_a` back through `CNOT(data_i → a)` for each `i∈supp` yields `(∏_{i∈supp} Z_i) · Z_a = S · Z_a`. Hence measuring `Z_a` measures `S` on the data register. Everything is Z-type, so no `Y` arises and the global phase stays `+1` throughout. ## The CNOT symplectic rule On per-qubit (x,z) bits, `CNOT(control=c, target=t)` acts by x_t ↦ x_t ⊕ x_c (control X spreads to target) z_c ↦ z_c ⊕ z_t (target Z spreads to control) with `x_c`, `z_t` unchanged. Equivalently the transfer table: `X_c ↦ X_c X_t`, `Z_t ↦ Z_c Z_t`, `X_t` and `Z_c` fixed. ## Where this fits in the stack This is the GATE-LEVEL rung: the physical ancilla+CNOT+measure circuit realizes one stabilizer measurement (PPM). The full Hilbert-space faithfulness of the Heisenberg/Pauli-conjugation picture is the once-proven Gottesman–Knill bridge (cited residue — we work in the symplectic Pauli algebra, which that bridge certifies is faithful to the state action). Rungs above this one: `QEC.CSSCode.syndrome_circuit_implements_code` — the code (many stabilizers measured together) `SurgeryCorrect.surgery_implements_logical_measurement` — logical PPM via lattice surgery `Corpus.ShorPPMEndToEnd` — Shor's algorithm end-to-end No Mathlib. Pure Bool / Nat / List. Decidable everywhere.
deftoSym
def toSym : Pauli → Bool × Bool
  | .I => (false, false)
  | .X => (true,  false)
  | .Z => (false, true)
  | .Y => (true,  true)
`(x,z)` symplectic bits of a single-qubit Pauli: `I = (F,F)`, `X = (T,F)`, `Z = (F,T)`, `Y = (T,T)`.
defofSym
def ofSym : Bool × Bool → Pauli
  | (false, false) => .I
  | (true,  false) => .X
  | (false, true)  => .Z
  | (true,  true)  => .Y
Inverse of `toSym`.
theoremofSym_toSym
theorem ofSym_toSym (p : Pauli) : ofSym (toSym p) = p
`ofSym` is a left inverse of `toSym` — the symplectic encoding is lossless.
defcnotConj
def cnotConj (c t : Nat) (p : PauliString) : PauliString
Conjugate `p` by `CNOT(control=c, target=t)`: read the `(x,z)` bits at positions `c` and `t`, update them by `x_t ⊕= x_c` and `z_c ⊕= z_t` (with `x_c`, `z_t` fixed), and write the new Paulis back. Implemented via `List.getD`/`List.set` over `p.ops`. Out-of- range indices read as `I` (getD default) and writes are no-ops, so the definition is total.
example(example)
example : cnotConj 0 1 ⟨Phase.plus, [Pauli.X, Pauli.I]⟩
    = ⟨Phase.plus, [Pauli.X, Pauli.X]⟩
`X⊗I ↦ X⊗X` (control X spreads to target).
example(example)
example : cnotConj 0 1 ⟨Phase.plus, [Pauli.I, Pauli.Z]⟩
    = ⟨Phase.plus, [Pauli.Z, Pauli.Z]⟩
`I⊗Z ↦ Z⊗Z` (target Z spreads to control).
example(example)
example : cnotConj 0 1 ⟨Phase.plus, [Pauli.Z, Pauli.I]⟩
    = ⟨Phase.plus, [Pauli.Z, Pauli.I]⟩
`Z⊗I ↦ Z⊗I` (control Z fixed).
example(example)
example : cnotConj 0 1 ⟨Phase.plus, [Pauli.I, Pauli.X]⟩
    = ⟨Phase.plus, [Pauli.I, Pauli.X]⟩
`I⊗X ↦ I⊗X` (target X fixed).
defmeasGadgetConj
def measGadgetConj (supp : List Nat) (a : Nat) (p : PauliString) : PauliString
Conjugate the ancilla observable `Z_a` back through the gadget's CNOTs `CNOT(data_i → a)` for each `i` in `supp`. In the Heisenberg picture the result is the observable that `measure Z_a` actually measures on the input register, namely `(∏_{i∈supp} Z_i) · Z_a`.
theoremmeasGadget_measures_Z0Z1
theorem measGadget_measures_Z0Z1 :
    measGadgetConj [0, 1] 2 ⟨Phase.plus, [Pauli.I, Pauli.I, Pauli.Z]⟩
      = ⟨Phase.plus, [Pauli.Z, Pauli.Z, Pauli.Z]⟩
GATE-LEVEL gadget: the ancilla+CNOT(0→2)+CNOT(1→2)+measure-Z₂ circuit measures the stabilizer `Z₀Z₁`. In the Heisenberg picture the measured `Z₂` becomes `Z₀Z₁Z₂` — the `Z₀Z₁` part is the stabilizer measured on the 2-qubit data register; the trailing `Z₂` is the ancilla's own observable.
theoremmeasGadget_measures_Z0Z1Z2
theorem measGadget_measures_Z0Z1Z2 :
    measGadgetConj [0, 1, 2] 3
        ⟨Phase.plus, [Pauli.I, Pauli.I, Pauli.I, Pauli.Z]⟩
      = ⟨Phase.plus, [Pauli.Z, Pauli.Z, Pauli.Z, Pauli.Z]⟩
GATE-LEVEL gadget (3-body): the ancilla+CNOT(0→3)+CNOT(1→3) +CNOT(2→3)+measure-Z₃ circuit measures the stabilizer `Z₀Z₁Z₂`. The measured `Z₃` becomes `Z₀Z₁Z₂Z₃`.
theoremcnot_ctrl
theorem cnot_ctrl (p : PauliString) (i a : Nat) (hi : i < p.ops.length)
    (hci : p.ops.getD i .I = Pauli.I) (hca : p.ops.getD a .I = Pauli.Z) :
    (cnotConj i a p).ops.getD i .I = Pauli.Z
`CNOT(i → a)` turns a control reading `I` into `Z` when the ancilla `a` reads `Z` (control Z spreads back from the target, since the target Z is mirrored onto the control).
theoremcnot_anc
theorem cnot_anc (p : PauliString) (i a : Nat) (ha : a < p.ops.length)
    (hci : p.ops.getD i .I = Pauli.I) (hca : p.ops.getD a .I = Pauli.Z) :
    (cnotConj i a p).ops.getD a .I = Pauli.Z
`CNOT(i → a)` leaves the ancilla reading `Z` when the control reads `I` (the control X part that would spread to the target is absent, so the ancilla's Z is untouched).
theoremcnot_other
theorem cnot_other (p : PauliString) (c t j : Nat) (hjc : j ≠ c) (hjt : j ≠ t) :
    (cnotConj c t p).ops.getD j .I = p.ops.getD j .I
`CNOT(c → t)` leaves every position other than `c` and `t` untouched.
theoremcnot_len
theorem cnot_len (p : PauliString) (c t : Nat) :
    (cnotConj c t p).ops.length = p.ops.length
`cnotConj` preserves the register length.
theoremcnot_phase
theorem cnot_phase (p : PauliString) (c t : Nat) :
    (cnotConj c t p).phase = p.phase
`cnotConj` preserves the global phase (Z-type / sign-free).
theoremgadget_len
theorem gadget_len (supp : List Nat) (a : Nat) (p : PauliString) :
    (measGadgetConj supp a p).ops.length = p.ops.length
The gadget preserves the register length.
theoremgadget_phase
theorem gadget_phase (supp : List Nat) (a : Nat) (p : PauliString) :
    (measGadgetConj supp a p).phase = p.phase
The gadget preserves the global phase (everything is Z-type, so no `±i` factor ever arises).
theoremgadget_untouched
theorem gadget_untouched (supp : List Nat) (a : Nat) (j : Nat) (hja : j ≠ a) :
    ∀ (p : PauliString), j ∉ supp →
      (measGadgetConj supp a p).ops.getD j .I = p.ops.getD j .I
Positions outside the support and `≠ a` are untouched by the whole gadget.
theoremgadget_anc
theorem gadget_anc (supp : List Nat) (a : Nat) :
    ∀ (p : PauliString), a < p.ops.length → a ∉ supp → supp.Nodup →
      p.ops.getD a .I = Pauli.Z → (∀ i ∈ supp, p.ops.getD i .I = Pauli.I) →
      (measGadgetConj supp a p).ops.getD a .I = Pauli.Z
The ancilla observable stays `Z` through the whole gadget.
theoremgadget_ctrl
theorem gadget_ctrl (supp : List Nat) (a : Nat) :
    ∀ (p : PauliString), a < p.ops.length → a ∉ supp → supp.Nodup →
      p.ops.getD a .I = Pauli.Z → (∀ i ∈ supp, i < p.ops.length) →
      (∀ i ∈ supp, p.ops.getD i .I = Pauli.I) →
      ∀ k ∈ supp, (measGadgetConj supp a p).ops.getD k .I = Pauli.Z
Every support qubit `k ∈ supp` ends up reading `Z`.
theoremmeasGadget_characterization
theorem measGadget_characterization
    (supp : List Nat) (a : Nat) (p : PauliString)
    (ha : a < p.ops.length) (hanc : a ∉ supp) (hnd : supp.Nodup)
    (hca : p.ops.getD a .I = Pauli.Z)
    (hrange : ∀ i ∈ supp, i < p.ops.length)
    (hctrl : ∀ i ∈ supp, p.ops.getD i .I = Pauli.I) :
    (∀ k ∈ supp, (measGadgetConj supp a p).ops.getD k .I = Pauli.Z)
    ∧ (measGadgetConj supp a p).ops.getD a .I = Pauli.Z
    ∧ (∀ j, j ≠ a → j ∉ supp →
        (measGadgetConj supp a p).ops.getD j .I = p.ops.getD j .I)
*Parametric gate-level gadget theorem.** Running the ancilla+CNOT(data_i→a for i∈supp)+measure-Zₐ circuit and conjugating the measured `Z_a` back through it yields, on the canonical Z-type input, an observable that reads `Z` on every support qubit and on the ancilla, and is untouched elsewhere. Concretely, for any `j`: if `j = a` or `j ∈ supp`, the conjugated observable reads `Z`; otherwise it equals the input's reading at `j`. This is the general statement instantiated by the concrete `measGadget_measures_Z0Z1` / `..._Z0Z1Z2` `decide` theorems above: the gate circuit measures exactly the Z-type stabilizer `∏_{i∈supp} Z_i` on the data register.
defxMeasGadgetConj
def xMeasGadgetConj (supp : List Nat) (a : Nat) (p : PauliString) : PauliString
Conjugate the ancilla observable `X_a` back through the X-syndrome gadget's CNOTs `CNOT(a → data_i)` for `i` in `supp` (control = ancilla). In the Heisenberg picture the result is the observable that `measure X_a` actually measures on the input register, namely `(∏_{i∈supp} X_i) · X_a`.
theoremxMeasGadget_measures_X0X1
theorem xMeasGadget_measures_X0X1 :
    xMeasGadgetConj [0, 1] 2 ⟨Phase.plus, [Pauli.I, Pauli.I, Pauli.X]⟩
      = ⟨Phase.plus, [Pauli.X, Pauli.X, Pauli.X]⟩
GATE-LEVEL X gadget: the ancilla(|+⟩)+CNOT(2→0)+CNOT(2→1) +measure-X₂ circuit measures the X-stabilizer `X₀X₁`. In the Heisenberg picture the measured `X₂` becomes `X₀X₁X₂` — the `X₀X₁` part is the stabilizer measured on the 2-qubit data register; the trailing `X₂` is the ancilla's own observable.
theoremxMeasGadget_measures_X0X1X2
theorem xMeasGadget_measures_X0X1X2 :
    xMeasGadgetConj [0, 1, 2] 3
        ⟨Phase.plus, [Pauli.I, Pauli.I, Pauli.I, Pauli.X]⟩
      = ⟨Phase.plus, [Pauli.X, Pauli.X, Pauli.X, Pauli.X]⟩
GATE-LEVEL X gadget (3-body): the ancilla(|+⟩)+CNOT(3→0) +CNOT(3→1)+CNOT(3→2)+measure-X₃ circuit measures the X-stabilizer `X₀X₁X₂`. The measured `X₃` becomes `X₀X₁X₂X₃`.
theoremcnot_x_tgt
theorem cnot_x_tgt (p : PauliString) (i a : Nat) (hi : i < p.ops.length)
    (hti : p.ops.getD i .I = Pauli.I) (hca : p.ops.getD a .I = Pauli.X) :
    (cnotConj a i p).ops.getD i .I = Pauli.X
`CNOT(a → i)` turns a target `i` reading `I` into `X` when the ancilla control `a` reads `X` (control X spreads to the target, `x_t ⊕= x_c`).
theoremcnot_x_anc
theorem cnot_x_anc (p : PauliString) (i a : Nat) (ha : a < p.ops.length)
    (hti : p.ops.getD i .I = Pauli.I) (hca : p.ops.getD a .I = Pauli.X) :
    (cnotConj a i p).ops.getD a .I = Pauli.X
`CNOT(a → i)` leaves the ancilla control `a` reading `X` (the control's own `x_c` bit is unchanged by the conjugation).
theoremxgadget_len
theorem xgadget_len (supp : List Nat) (a : Nat) (p : PauliString) :
    (xMeasGadgetConj supp a p).ops.length = p.ops.length
The X gadget preserves the register length.
theoremxgadget_phase
theorem xgadget_phase (supp : List Nat) (a : Nat) (p : PauliString) :
    (xMeasGadgetConj supp a p).phase = p.phase
The X gadget preserves the global phase (everything is X-type).
theoremxgadget_untouched
theorem xgadget_untouched (supp : List Nat) (a : Nat) (j : Nat) (hja : j ≠ a) :
    ∀ (p : PauliString), j ∉ supp →
      (xMeasGadgetConj supp a p).ops.getD j .I = p.ops.getD j .I
Positions outside the support and `≠ a` are untouched by the X gadget.
theoremxgadget_anc
theorem xgadget_anc (supp : List Nat) (a : Nat) :
    ∀ (p : PauliString), a < p.ops.length → a ∉ supp → supp.Nodup →
      p.ops.getD a .I = Pauli.X → (∀ i ∈ supp, p.ops.getD i .I = Pauli.I) →
      (xMeasGadgetConj supp a p).ops.getD a .I = Pauli.X
The ancilla observable stays `X` through the whole X gadget.
theoremxgadget_ctrl
theorem xgadget_ctrl (supp : List Nat) (a : Nat) :
    ∀ (p : PauliString), a < p.ops.length → a ∉ supp → supp.Nodup →
      p.ops.getD a .I = Pauli.X → (∀ i ∈ supp, i < p.ops.length) →
      (∀ i ∈ supp, p.ops.getD i .I = Pauli.I) →
      ∀ k ∈ supp, (xMeasGadgetConj supp a p).ops.getD k .I = Pauli.X
Every support qubit `k ∈ supp` ends up reading `X`.
theoremxMeasGadget_characterization
theorem xMeasGadget_characterization
    (supp : List Nat) (a : Nat) (p : PauliString)
    (ha : a < p.ops.length) (hanc : a ∉ supp) (hnd : supp.Nodup)
    (hca : p.ops.getD a .I = Pauli.X)
    (hrange : ∀ i ∈ supp, i < p.ops.length)
    (hctrl : ∀ i ∈ supp, p.ops.getD i .I = Pauli.I) :
    (∀ k ∈ supp, (xMeasGadgetConj supp a p).ops.getD k .I = Pauli.X)
    ∧ (xMeasGadgetConj supp a p).ops.getD a .I = Pauli.X
    ∧ (∀ j, j ≠ a → j ∉ supp →
        (xMeasGadgetConj supp a p).ops.getD j .I = p.ops.getD j .I)
*Parametric gate-level X gadget theorem.** Running the ancilla(|+⟩)+CNOT(a→data_i for i∈supp)+measure-Xₐ circuit and conjugating the measured `X_a` back through it yields, on the canonical X-type input, an observable that reads `X` on every support qubit and on the ancilla, and is untouched elsewhere. This is the exact dual of `measGadget_characterization` (§4): the gate circuit measures exactly the X-type stabilizer `∏_{i∈supp} X_i` on the data register. Instantiated by the concrete `xMeasGadget_measures_X0X1` / `..._X0X1X2` `decide` theorems above.

FormalRV.PPM.CliffordPPMRules

FormalRV/PPM/CliffordPPMRules.lean
FormalRV.PPM.CliffordPPMRules — faithful, stabilizer-level correctness of Clifford gate implementations by Pauli measurements with back-action (Heisenberg picture), via the real Gottesman update `apply_PPM_pos` / `apply_PPM_neg` — NOT the deterministic Boolean stand-in. ## The H rule (gate teleportation) The logical Hadamard is implemented by consuming a 2-qubit `|H⟩` resource state (stabilised by `X⊗Z` and `Z⊗X` on the ancilla pair `(a,b)`) and performing two Pauli-product measurements on the data `d` and ancilla `a`: measure X_d X_a , then measure Z_d Z_a . Tracking the stabiliser through these REAL measurements (Gottesman `apply_PPM_pos`), the output qubit `b` ends up in `H|ψ⟩`: |0⟩ ↦ |+⟩, |1⟩ ↦ |−⟩, |+⟩ ↦ |0⟩, |−⟩ ↦ |1⟩. Each is the Heisenberg fact that `H` swaps `X ↔ Z` (the `b`-qubit effective stabiliser is the `H`-conjugate of the input's), proved by `decide` on the actual stabiliser evolution. ## Faithfulness / back-action `apply_PPM_pos` / `apply_PPM_neg` ARE the two measurement-outcome branches of the Gottesman update; the `+1/+1` branch shown here has trivial Pauli correction, and the other outcome branches differ only by a standard Pauli byproduct (the back-action), tracked classically in the Pauli frame. This is the genuine stabiliser semantics, not a reverse-engineered Boolean interpretation.
defhRes_XZ
def hRes_XZ : PauliString
`|H⟩` resource stabiliser `X⊗Z` on `(a,b)`.
defhRes_ZX
def hRes_ZX : PauliString
`|H⟩` resource stabiliser `Z⊗X` on `(a,b)`.
defmeasXX
def measXX : PauliString
First measurement: `X_d X_a`.
defmeasZZ
def measZZ : PauliString
Second measurement: `Z_d Z_a`.
defhGadget
def hGadget (s : StabilizerState) : StabilizerState
The H-teleportation gadget (`+1/+1` outcome branch): two real Gottesman Pauli measurements.
definput0
def input0     : StabilizerState
definput1
def input1     : StabilizerState
definputPlus
def inputPlus  : StabilizerState
definputMinus
def inputMinus : StabilizerState
defoutputB
def outputB (s : StabilizerState) : Option (Phase × Pauli)
theoremhRule_0_gives_plus
theorem hRule_0_gives_plus :
    outputB (hGadget input0) = some (.plus, .X)
`H|0⟩ = |+⟩`: output `b` stabilised by `+X`.
theoremhRule_1_gives_minus
theorem hRule_1_gives_minus :
    outputB (hGadget input1) = some (.minus, .X)
`H|1⟩ = |−⟩`: output `b` stabilised by `−X`.
theoremhRule_plus_gives_0
theorem hRule_plus_gives_0 :
    outputB (hGadget inputPlus) = some (.plus, .Z)
`H|+⟩ = |0⟩`: output `b` stabilised by `+Z`.
theoremhRule_minus_gives_1
theorem hRule_minus_gives_1 :
    outputB (hGadget inputMinus) = some (.minus, .Z)
`H|−⟩ = |1⟩`: output `b` stabilised by `−Z`.
theoremhRule_truth_table
theorem hRule_truth_table :
    outputB (hGadget input0)     = some (.plus,  .X)
  ∧ outputB (hGadget input1)     = some (.minus, .X)
  ∧ outputB (hGadget inputPlus)  = some (.plus,  .Z)
  ∧ outputB (hGadget inputMinus) = some (.minus, .Z)
*The H rule, packaged.** On the four single-qubit basis inputs the measurement gadget produces exactly `H|ψ⟩` on the output qubit: `Z`-eigenstates ↦ `X`-eigenstates and vice versa (H swaps `X ↔ Z`).
theoremhGadget_valid_0
theorem hGadget_valid_0 :
    StabilizerState.valid (hGadget input0) 3 = true
theoremhGadget_valid_1
theorem hGadget_valid_1 :
    StabilizerState.valid (hGadget input1) 3 = true
theoremhGadget_valid_plus
theorem hGadget_valid_plus :
    StabilizerState.valid (hGadget inputPlus) 3 = true
theoremhGadget_valid_minus
theorem hGadget_valid_minus :
    StabilizerState.valid (hGadget inputMinus) 3 = true
theoremhGadget_measZZ_mem_input0
theorem hGadget_measZZ_mem_input0 :
    measZZ ∈ hGadget input0
The measured Pauli `Z_d Z_a` is a generator of every output state (the projective-measurement membership law, here at the gate level). Both Bell generators witness the measurement back-action.
defcnotMeasZZ
def cnotMeasZZ   : PauliString
defcnotMeasXX
def cnotMeasXX   : PauliString
defcnotMeasZanc
def cnotMeasZanc : PauliString
defcnotGadget
def cnotGadget (s : StabilizerState) : StabilizerState
The CNOT gadget (`+1` outcome branch): three real Gottesman Pauli measurements consuming a `|+⟩` ancilla.
defcnot_in00
def cnot_in00 : StabilizerState
Input `|c t⟩_{c,t} ⊗ |+⟩_anc`. `anc = qubit 1`.
defcnot_in01
def cnot_in01 : StabilizerState
defcnot_in10
def cnot_in10 : StabilizerState
defcnot_in11
def cnot_in11 : StabilizerState
theoremcnotRule_00
theorem cnotRule_00 :
    cnotGadget cnot_in00
      = [⟨.plus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus, [.Z,.Z,.Z]⟩]
`CNOT|00⟩ = |00⟩`.
theoremcnotRule_01
theorem cnotRule_01 :
    cnotGadget cnot_in01
      = [⟨.plus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
`CNOT|01⟩ = |01⟩` (control 0 ⇒ target unchanged).
theoremcnotRule_10
theorem cnotRule_10 :
    cnotGadget cnot_in10
      = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus, [.Z,.Z,.Z]⟩]
`CNOT|10⟩ = |11⟩` (control 1 ⇒ target flips).
theoremcnotRule_11
theorem cnotRule_11 :
    cnotGadget cnot_in11
      = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
`CNOT|11⟩ = |10⟩` (control 1 ⇒ target flips).
theoremcnotRule_truth_table
theorem cnotRule_truth_table :
    cnotGadget cnot_in00 = [⟨.plus,  [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus,  [.Z,.Z,.Z]⟩]
  ∧ cnotGadget cnot_in01 = [⟨.plus,  [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
  ∧ cnotGadget cnot_in10 = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus,  [.Z,.Z,.Z]⟩]
  ∧ cnotGadget cnot_in11 = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
*The CNOT rule, packaged.** On all four computational-basis inputs the measurement gadget produces the CNOT image `|c t⟩ ↦ |c, t ⊕ c⟩` (read from the generator signs as explained above).
theoremcnotGadget_valid_00
theorem cnotGadget_valid_00 :
    StabilizerState.valid (cnotGadget cnot_in00) 3 = true
theoremcnotGadget_valid_11
theorem cnotGadget_valid_11 :
    StabilizerState.valid (cnotGadget cnot_in11) 3 = true
defsRes_XY
def sRes_XY : PauliString
`|S⟩` resource stabiliser `X⊗Y` on `(a,b)`.
defsRes_ZZ
def sRes_ZZ : PauliString
`|S⟩` resource stabiliser `Z⊗Z` on `(a,b)`.
defsGadget
def sGadget (s : StabilizerState) : StabilizerState
The S gadget uses the SAME measurements as the H gadget; only the resource state differs.
defsInput0
def sInput0     : StabilizerState
defsInput1
def sInput1     : StabilizerState
defsInputPlus
def sInputPlus  : StabilizerState
defsInputMinus
def sInputMinus : StabilizerState
theoremsRule_0_gives_0
theorem sRule_0_gives_0 :
    outputB (sGadget sInput0) = some (.plus, .Z)
`S|0⟩ = |0⟩`: output `b` stabilised by `+Z`.
theoremsRule_1_gives_1
theorem sRule_1_gives_1 :
    outputB (sGadget sInput1) = some (.minus, .Z)
`S|1⟩ = |1⟩` (up to global phase): output `b` stabilised by `−Z`.
theoremsRule_plus_gives_plusI
theorem sRule_plus_gives_plusI :
    outputB (sGadget sInputPlus) = some (.plus, .Y)
`S|+⟩ = |+i⟩`: output `b` stabilised by `+Y`.
theoremsRule_minus_gives_minusI
theorem sRule_minus_gives_minusI :
    outputB (sGadget sInputMinus) = some (.minus, .Y)
`S|−⟩ = |−i⟩`: output `b` stabilised by `−Y`.
theoremsRule_truth_table
theorem sRule_truth_table :
    outputB (sGadget sInput0)     = some (.plus,  .Z)
  ∧ outputB (sGadget sInput1)     = some (.minus, .Z)
  ∧ outputB (sGadget sInputPlus)  = some (.plus,  .Y)
  ∧ outputB (sGadget sInputMinus) = some (.minus, .Y)
*The S rule, packaged.** On the four single-qubit basis inputs the measurement gadget produces `S|ψ⟩` on the output qubit: `S` fixes the `Z`-eigenstates and maps the `X`-eigenstates to `Y`-eigenstates (`S` conjugates `X ↦ Y`, `Z ↦ Z`).
theoremsGadget_valid_0
theorem sGadget_valid_0 :
    StabilizerState.valid (sGadget sInput0) 3 = true
theoremsGadget_valid_plus
theorem sGadget_valid_plus :
    StabilizerState.valid (sGadget sInputPlus) 3 = true

FormalRV.PPM.EightTToCCZScheme

FormalRV/PPM/EightTToCCZScheme.lean
FormalRV.PPM.EightTToCCZScheme — the famous 8T→CCZ (7-T) gate identity, proved sorry-free from first principles. ## What this file proves The standard fault-tolerant way to realise a `CCZ` (and hence a Toffoli, via `CCX = H_c · CCZ · H_c`) is to spend T-gates: the diagonal phase of `CCZ` on a computational basis state `|abc⟩` is `(-1)^{a∧b∧c}`, and this phase is produced by the **phase-polynomial** of seven conditional `T`/`T†` rotations (one per nonempty parity of the three inputs): T_a · T_b · T_c · T†_{a⊕b} · T†_{b⊕c} · T†_{a⊕c} · T_{a⊕b⊕c}. Writing `ω = e^{iπ/4}` (an 8th root of unity, the T phase), the net phase on `|abc⟩` is `ω^{E(a,b,c)}` where E(a,b,c) = [a]+[b]+[c] + 7[a⊕b] + 7[b⊕c] + 7[a⊕c] + [a⊕b⊕c] (the `7` is `T† = ω⁻¹ = ω⁷`). The content of the identity is the *decidable** congruence E(a,b,c) ≡ 4·[a∧b∧c] (mod 8), proved by `decide` over the 8 Boolean inputs, which gives `ω^{E} = (ω⁴)^{[a∧b∧c]} = (-1)^{[a∧b∧c]}` — exactly the `CCZ` phase. Headline results: `eightT_ccz_phase` — the scalar phase-polynomial identity. `tDecompMat_eq_cczMat` — the matrix-level gate identity: the diagonal unitary built from the seven T-phases equals the `CCZ` matrix. ## Honesty boundary This is the **gate-level unitary identity** for `CCZ`. The `CNOT` routing that physically computes the parities `a⊕b`, … into the register (and uncomputes them) is the standard Clifford wrapper; on the three data qubits the net unitary is exactly the diagonal phase proved here, so no spurious phases remain. "8 T" vs "7 T": seven conditional rotations appear in the phase polynomial; the *eighth* T is the catalyst / magic-state convention used by distillation accounting (`Factory.EightTToCCZSpec`). This file proves the *phase identity*; the resource count is a separate, already-modelled concern. Magic-state *distillation* correctness and the physical T-state are NOT in scope here — this is the logical Clifford+T gate identity.
defComplex.exp
noncomputable def ω : ℂ
The T-gate phase `ω = exp(iπ/4)`, a primitive 8th root of unity.
theorem_pow_four
theorem ω_pow_four : ω ^ 4 = -1
theorem_pow_eight
theorem ω_pow_eight : ω ^ 8 = 1
theorem_pow_mod_eight
theorem ω_pow_mod_eight (n : Nat) : ω ^ n = ω ^ (n % 8)
`ω^n` depends only on `n mod 8`.
defbitN
def bitN (x : Bool) : Nat
Boolean → {0,1} indicator (as a `Nat`).
deftExp
def tExp (a b c : Bool) : Nat
The net T-phase exponent of the seven-rotation `CCZ` phase polynomial on input `|abc⟩`. `T = ω`, `T† = ω⁻¹ = ω⁷` (hence the `7·` coefficients on the pair parities).
theoremtExp_mod_eight
theorem tExp_mod_eight (a b c : Bool) :
    tExp a b c % 8 = 4 * bitN (a && b && c)
*The decidable core**: the phase-polynomial exponent is `≡ 4·[a∧b∧c]` modulo 8. Proved by `decide` over the eight Boolean inputs.
defcczPhase
def cczPhase (a b c : Bool) : ℂ
The diagonal phase that `CCZ` applies to `|abc⟩`: `-1` iff all three bits are set, else `+1`.
theoremeightT_ccz_phase
theorem eightT_ccz_phase (a b c : Bool) :
    ω ^ (tExp a b c) = cczPhase a b c
*Headline (scalar form).** The seven-T phase polynomial produces exactly the `CCZ` phase on every computational basis input.
defcczMat
noncomputable def cczMat : Matrix (Fin 8) (Fin 8) ℂ
The `CCZ` unitary as an 8×8 diagonal matrix: identity except a `-1` phase on `|111⟩` (index 7).
defaOf
def aOf (i : Fin 8) : Bool
Decode the high / mid / low bit of a basis index `i < 8` (`i = 4·a + 2·b + c`, big-endian).
defbOf
def bOf (i : Fin 8) : Bool
defcOf
def cOf (i : Fin 8) : Bool
deftDecompMat
noncomputable def tDecompMat : Matrix (Fin 8) (Fin 8) ℂ
The diagonal unitary assembled from the seven-T phase polynomial.
theoremtDecompMat_eq_cczMat
theorem tDecompMat_eq_cczMat : tDecompMat = cczMat
*Headline (matrix form).** The T-phase-polynomial diagonal unitary equals* the `CCZ` matrix. This is the famous 8T→CCZ gate identity at the unitary level.

FormalRV.PPM.FactoryHierarchy

FormalRV/PPM/FactoryHierarchy.lean
FormalRV.Framework.FactoryHierarchy — the user-directed abstraction split between *atomic* magic-state factories and *implementer-specified* CCZ constructions. ## Per John's 2026-05-25 directive > "For factory, I think we can set T-factory, such as > Cultivation, a black block that takes some time and > space. But if we use 8T-CCZ, then user actually need > to specify how they want to implement it. The only > atomic black box is T-distillation/Cultivation." Hence two factory specs: 1. **Atomic factories** (`AtomicFactorySpec`). T-state distillation, CCZ cultivation, magic-state factories whose internal distillation circuit we do NOT formalise. They consume time + space; their output is requested via a single `RequestMagicState` SysCall. 2. **8T-to-CCZ composition** (`EightTToCCZSpec`). When the implementer chooses to BUILD a CCZ state from 8 T states + Clifford glue (NOT cultivation), they must submit: (a) The T-factory zone id (an atomic factory). (b) The CCZ output zone id. (c) The 8 T-request SysCalls within the CCZ window. (d) (Future) The Clifford-glue circuit. The framework verifies that the composition is *structurally honest* — at minimum, the 8 T-state requests exist within the CCZ's production window. Semantic correctness (the Clifford circuit actually produces |CCZ⟩) is a deeper verification we don't claim here. No Mathlib. Pure Bool / Nat / List. Decidable.
inductiveMagicStateKind
inductive MagicStateKind
  | T
  | CCZ
  deriving DecidableEq, Repr
The two kinds of magic state the framework distinguishes: T (the universal atomic resource) and CCZ (which CAN be produced atomically by cultivation OR composed from 8 T states).
instanceInhabited
instance : Inhabited MagicStateKind
structureAtomicFactorySpec
structure AtomicFactorySpec
One atomic factory — either T or CCZ cultivation. Internal distillation circuit is NOT specified; the framework accepts its outputs on trust. The implementer DECLARES these parameters — the framework cannot derive them without modelling the underlying distillation circuit (which is out of scope per the "atomic black box" rule).
defmax_outputs_in_window
def max_outputs_in_window (f : AtomicFactorySpec) (window_us : Nat) : Nat
Maximum number of outputs over a window of `window_us` microseconds, assuming DETERMINISTIC output and pipeline already full. Used by I4 throughput checking as the upper bound on supply.
defexpected_outputs_in_window
def expected_outputs_in_window
    (f : AtomicFactorySpec) (window_us : Nat) : Nat
Expected number of outputs over a window, accounting for success probability. Approximates `(window_us / time_per_state_us) × success_prob`. Encoded in ppm units to stay in Nat: expected_outputs = (window_us / time_per_state_us) × success_probability_ppm / 1_000_000. For deterministic factories (`success_probability_ppm = 1_000_000`) this equals `max_outputs_in_window`.
defthroughput_per_ms_x1000
def throughput_per_ms_x1000 (f : AtomicFactorySpec) : Nat
Throughput in outputs per millisecond × 1000 (fixed point integer for Nat). throughput_x1000 = 1_000_000_000 × success_probability_ppm / (time_per_state_us × 1_000_000) = 1000 × success_probability_ppm / time_per_state_us.
deftotal_latency_for_n_outputs
def total_latency_for_n_outputs (f : AtomicFactorySpec) (n : Nat) : Nat
The total latency to deliver `n` outputs. `total = startup_latency + (n - 1) × time_per_state` (pipeline depth for the first, then steady state).
structureEightTToCCZSpec
structure EightTToCCZSpec
The implementer's declaration of an 8T-to-CCZ build.
deft_requests_in_window
def t_requests_in_window (spec : EightTToCCZSpec) (sched : List SysCall) : Nat
Count `RequestMagicState` SysCalls targeting `t_factory_zone` whose entire `[begin_us, end_us)` lies within the build window.
defhas_eight_t_requests
def has_eight_t_requests (spec : EightTToCCZSpec) (sched : List SysCall) : Bool
*Check 1.** Exactly 8 (or more — the implementer is free to over-request, e.g. for distillation post- selection) T-state requests target the T-factory zone inside the build window.
defwindow_well_formed
def window_well_formed (spec : EightTToCCZSpec) : Bool
*Check 2.** The build window is non-trivial (begin < end).
defdownstream_ccz_request
def downstream_ccz_request
    (spec : EightTToCCZSpec) (sched : List SysCall) : Bool
*Check 3.** There is exactly one downstream `RequestMagicState` to `ccz_output_zone` whose begin time equals `build_end_us` (the CCZ becomes available at the build's end).
defverifies
def verifies (spec : EightTToCCZSpec) (sched : List SysCall) : Bool
Headline: the 8T-to-CCZ build is honestly structural.
inductiveMagicFactory
inductive MagicFactory
  | atomic   (spec : AtomicFactorySpec)
  | composite (spec : EightTToCCZSpec)
  deriving Repr, Inhabited
defoutput_zone
def output_zone : MagicFactory → Nat
  | .atomic    s => s.zone_id
  | .composite s => s.ccz_output_zone
The zone id `RequestMagicState` SysCalls target.
defverifies
def verifies (f : MagicFactory) (sched : List SysCall) : Bool
Atomic factories are accepted by structure (no internals to check); composite factories must pass `EightTToCCZSpec.verifies`.
defcuccaro_n1_cultivation_factory
def cuccaro_n1_cultivation_factory : MagicFactory
defcuccaro_n1_gate3_eight_t
def cuccaro_n1_gate3_eight_t : EightTToCCZSpec
An illustrative 8T-to-CCZ spec for gate-3's CCZ (request at t=0, delivery at t=12_000, drawn from T-factory at zone 9). Just the spec — the schedule we'd need to submit to verify it must contain 8 T-requests inside [0, 12_000).

FormalRV.PPM.GE2021PPMSysInv

FormalRV/PPM/GE2021PPMSysInv.lean
FormalRV.Framework.GE2021PPMSysInv — a SMALL, CONCRETE PPM-block SysCall schedule whose resource numbers are DERIVED FROM the actual list of SysCalls (not typed in). ## Motivation — closing the spreadsheet gap `Corpus/GidneyEkera2021FullStackE2E.lean`'s `per_shot_runtime_us` is a TYPED-IN `Nat` field on `GE2021Submission`; its "verified" wallclock theorem `ge2021_per_shot_wallclock` reduces to the identity function applied to that typed-in value: per_shot_wallclock_us := sub.per_shot_runtime_us -- identity ge2021_per_shot_wallclock := (compute_resources concrete_submission).per_shot_wallclock_us = 18_360_000_000 -- = the typed-in Nat This file is the smallest reusable counter-example: a 16-SysCall PPM block where the wallclock and peak physical qubits are COMPUTED from the actual SysCall list (foldl over end_us, per-cycle active-atom count), and the four system-level invariants (I1 capacity + I2 exclusivity + I3 feedback latency + I3 decoder reaction + I4 factory throughput) are decide-closed on that list. ## What the PPM block represents One joint Pauli-product measurement M_{ZZ} between two logical qubits L0 (data qubit 0) and L1 (data qubit 50), via an ancilla qubit (atom 100), over τ_s = 3 syndrome-extraction rounds (minimum to verify the joint stabilizer's outcome bit via majority vote), plus one PauliFrameUpdate. Per round (5 SysCalls): 1. RequestFreshAncilla — allocate the joint-measurement ancilla 2. Gate2q 0 → 100 — controlled by L0's data qubit 3. Gate2q 50 → 100 — controlled by L1's data qubit 4. Measure 100 — read out the joint stabilizer 5. DecodeSyndrome r — classical reaction per round After 3 rounds: 16. PauliFrameUpdate 0 — apply correction based on the majority-vote XOR of the 3 outcomes Total: 16 SysCalls; wallclock = 16 µs; peak active qubits = 2 per cycle (a single Gate2q claims two atoms simultaneously). ## Anti-spreadsheet property Compare verbatim: GE2021FullStackE2E.lean: per_shot_wallclock_us := sub.per_shot_runtime_us -- IDENTITY theorem ge2021_per_shot_wallclock : compute_resources.per_shot_wallclock_us = 18_360_000_000 := by decide -- ↑ proves: the typed-in Nat equals itself. This file: def ppm_block_wallclock_us := ppm_block_syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0 theorem ppm_block_wallclock_is_derived : ppm_block_wallclock_us = ppm_block_syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0 := rfl -- ↑ proves: the wallclock is the foldl, not a typed-in value. No Mathlib. Pure Bool / Nat / List. Decidable.
defge2021_ppm_arch
def ge2021_ppm_arch : ZonedArch
theoremge2021_ppm_arch_zone_count
theorem ge2021_ppm_arch_zone_count :
    ge2021_ppm_arch.zones.length = 2
theoremge2021_ppm_arch_total
theorem ge2021_ppm_arch_total :
    ge2021_ppm_arch.total_sites = 200
defppm_round
def ppm_round (start_us : Nat) (decoder_id : Nat) : List SysCall
One round of the joint M_{ZZ} measurement. Five SysCalls starting at `start_us`, ending at `start_us + 5`.
theoremppm_round_count
theorem ppm_round_count (s d : Nat) : (ppm_round s d).length = 5
defppm_block_syscalls
def ppm_block_syscalls : List SysCall
The complete PPM block. Three rounds of the joint measurement at t = 0, 5, 10, then a PauliFrameUpdate at t = 15.
theoremppm_block_syscall_count
theorem ppm_block_syscall_count :
    ppm_block_syscalls.length = 16
defppm_block_wallclock_us
def ppm_block_wallclock_us : Nat
Wallclock = max end_us across all SysCalls. This is the KEY anti-spreadsheet definition: nothing typed in, no field on a struct — just the fold.
defppm_block_peak_physical_qubits
def ppm_block_peak_physical_qubits : Nat
Peak simultaneously-active physical qubits. For each distinct begin time `t` in the schedule, count atoms claimed by syscalls active at that instant; take the max across all such `t`s. This is the per-instant load that `capacity_per_cycle_ok` bounds against the per-zone capacities.
defppm_block_total_distinct_qubits
def ppm_block_total_distinct_qubits : Nat
Total distinct physical qubits TOUCHED by the schedule. Sums up the qubits referenced anywhere in any SysCall.
theoremppm_block_wallclock_is_derived
theorem ppm_block_wallclock_is_derived :
    ppm_block_wallclock_us =
      ppm_block_syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0
*The key anti-spreadsheet theorem.** Demonstrates the wallclock is computed from the SysCall stream, not copied from a submitted Nat field.
theoremppm_block_wallclock_value
theorem ppm_block_wallclock_value :
    ppm_block_wallclock_us = 16
theoremppm_block_peak_physical_qubits_value
theorem ppm_block_peak_physical_qubits_value :
    ppm_block_peak_physical_qubits = 2
theoremppm_block_total_distinct_qubits_value
theorem ppm_block_total_distinct_qubits_value :
    ppm_block_total_distinct_qubits = 3
theoremppm_block_capacity_in_arch_ok
theorem ppm_block_capacity_in_arch_ok :
    capacity_in_arch_ok ge2021_ppm_arch ppm_block_syscalls = true
theoremppm_block_capacity_per_cycle_ok
theorem ppm_block_capacity_per_cycle_ok :
    capacity_per_cycle_ok ge2021_ppm_arch ppm_block_syscalls = true
theoremppm_block_exclusivity_ok
theorem ppm_block_exclusivity_ok :
    exclusivity_ok ppm_block_syscalls = true
theoremppm_block_feedback_latency_ok
theorem ppm_block_feedback_latency_ok :
    feedback_latency_ok ge2021_ppm_arch.t_cycle_us ppm_block_syscalls = true
theoremppm_block_speed_limit_ok
theorem ppm_block_speed_limit_ok :
    speed_limit_ok ge2021_ppm_arch.v_max_um_per_us (fun _ => 0)
      ppm_block_syscalls = true
theoremppm_block_window_throughput_ok
theorem ppm_block_window_throughput_ok :
    window_throughput_ok ppm_block_syscalls 1000 1000 = true
theoremppm_block_decoder_react_ok
theorem ppm_block_decoder_react_ok :
    decoder_react_ok 10 ppm_block_syscalls = true
The patched decoder-reaction check (added to `ScheduleInvariantsExplicit.lean`): every `DecodeSyndrome` completes within `t_react_us` µs.
theoremppm_block_all_invariants_ok
theorem ppm_block_all_invariants_ok :
    all_invariants_ok ge2021_ppm_arch ppm_block_syscalls 1000 1000 (fun _ => 0) = true
The headline structural-correctness theorem: the 16-SysCall PPM block satisfies every system-level invariant on the GE2021-style architecture.
defcount_request_fresh_ancilla
def count_request_fresh_ancilla (sched : List SysCall) : Nat
defcount_gate2q
def count_gate2q (sched : List SysCall) : Nat
defcount_measure
def count_measure (sched : List SysCall) : Nat
defcount_decode_syndrome
def count_decode_syndrome (sched : List SysCall) : Nat
defcount_pauli_frame_update
def count_pauli_frame_update (sched : List SysCall) : Nat
theoremppm_block_count_request_fresh_ancilla
theorem ppm_block_count_request_fresh_ancilla :
    count_request_fresh_ancilla ppm_block_syscalls = 3
Three rounds × 1 RequestFreshAncilla each = 3.
theoremppm_block_count_gate2q
theorem ppm_block_count_gate2q :
    count_gate2q ppm_block_syscalls = 6
Three rounds × 2 Gate2q each = 6.
theoremppm_block_count_measure
theorem ppm_block_count_measure :
    count_measure ppm_block_syscalls = 3
Three rounds × 1 Measure each = 3.
theoremppm_block_count_decode_syndrome
theorem ppm_block_count_decode_syndrome :
    count_decode_syndrome ppm_block_syscalls = 3
Three rounds × 1 DecodeSyndrome each = 3.
theoremppm_block_count_pauli_frame_update
theorem ppm_block_count_pauli_frame_update :
    count_pauli_frame_update ppm_block_syscalls = 1
One PauliFrameUpdate at the end of the block.

FormalRV.PPM.GadgetChannel

FormalRV/PPM/GadgetChannel.lean
FormalRV.PPM.GadgetChannel — GAPS 1–4 (gadget channel), CLOSED for the T gate; CCZ all-zeros (000) branch delivered as the analogue. ## What this closes The measurement-based magic-state gadget (CNOT · Z-measure · feedback) is the workhorse of the PPM compilation: a T (resp. CCZ) gate is realized by consuming a magic state, performing a destructive Z-measurement on the ancilla, and applying an outcome-dependent Pauli/Clifford correction. Four things must hold for this to be a faithful realization of the unitary `U`: GAP 1 — *Per-outcome extraction.* Tracing out the ancilla against outcome `⟨b|`, the operator acting on the data register is a scalar times `U`. GAP 2 — *Born normalization.* The per-outcome scalars `c_b` satisfy `Σ_b |c_b|² = 1`, so the gadget is trace-preserving. GAP 3 — *Magic-injection / ancilla-extraction faithfulness.* The injection `I ⊗ |magic⟩` and extraction `I ⊗ ⟨b|` are the genuine tensor maps, so the extracted operator is DERIVED from the gadget theorem, not hand-asserted. GAP 4 — *Channel equality.* Summing over outcomes (with the GAP-2 fact), the data CHANNEL `Φ(ρ) = Σ_b K_b ρ K_b†` equals the unitary channel `U ρ U†`. All four are proved here for the T gate (`tChannel_eq_unitaryChannel`, refining `tKraus_eq_smul_U` + `tBorn_normSq_sum`). For CCZ, only the 000 (all-zeros) measurement branch is delivered (`cczKraus000_eq_smul_U`, per-outcome operator extraction); the other 7 outcomes need a CZ-correction primitive the repo lacks, so the full CCZ channel is out of scope here. No `sorry`, no new `axiom`.
deftGadgetOp
noncomputable def tGadgetOp (b : Bool) : Matrix (Fin 4) (Fin 4) ℂ
The full gadget operator on data⊗ancilla (4-dim) for outcome `b`: `S-correction · Z-measure · CNOT`.
definjectMagic
noncomputable def injectMagic : Matrix (Fin 4) (Fin 2) ℂ
`I_data ⊗ |T⟩` : maps a data state `ψ` to `ψ ⊗ᵥ |T⟩` (data = HIGH qubit).
defextractAnc
def extractAnc : Bool → Matrix (Fin 2) (Fin 4) ℂ
  | false => !![1, 0, 0, 0;
                0, 0, 1, 0]
  | true  => !![0, 1, 0, 0;
                0, 0, 0, 1]
`I_data ⊗ ⟨b|` : contracts the ancilla against `⟨b|`.
theoreminjectMagic_apply
theorem injectMagic_apply (ψ : StateVec 1) :
    injectMagic * ψ = ψ ⊗ᵥ tKet
theoremextractAnc_kron
theorem extractAnc_kron (ψd : StateVec 1) (b : Bool) :
    extractAnc b * (ψd ⊗ᵥ tAnc b) = ψd
deftKraus
noncomputable def tKraus (b : Bool) : Matrix (Fin 2) (Fin 2) ℂ
`Kraus_b := (I ⊗ ⟨b|) · G_b · (I ⊗ |T⟩)`, a 2×2 matrix on the DATA register (ancilla discarded, global gadget matrix).
theoremtKraus_eq_smul_U
theorem tKraus_eq_smul_U (b : Bool) :
    tKraus b = tBorn b • tMat
*GAPS 1+3.** The extracted data operator equals the Born scalar times the T-gate matrix: `Kraus_b = tBorn b • tMat`. Derived from `t_gadget_with_feedback`.
theoremnormSq_
theorem normSq_ω : Complex.normSq ω = 1
theoremtBorn_normSq_sum
theorem tBorn_normSq_sum :
    Complex.normSq (tBorn false) + Complex.normSq (tBorn true) = 1
*GAP 2.** `Σ_b |c_b|² = |1/√2|² + |ω/√2|² = 1`.
deftChannel
noncomputable def tChannel (ρ : Matrix (Fin 2) (Fin 2) ℂ) : Matrix (Fin 2) (Fin 2) ℂ
`Φ(ρ) := Σ_b Kraus_b · ρ · Kraus_b†` (ancilla traced out; outcomes summed).
deftUnitaryChannel
noncomputable def tUnitaryChannel (ρ : Matrix (Fin 2) (Fin 2) ℂ) :
    Matrix (Fin 2) (Fin 2) ℂ
The unitary channel of the T gate: `ρ ↦ U · ρ · U†`.
theoremtChannel_eq_unitaryChannel
theorem tChannel_eq_unitaryChannel (ρ : Matrix (Fin 2) (Fin 2) ℂ) :
    tChannel ρ = tUnitaryChannel ρ
*GAPS 1–4 combined.** The measurement gadget's data channel IS the unitary channel: `Φ(ρ) = Σ_b Kraus_b · ρ · Kraus_b† = U · ρ · U†`.
defcczGadgetOp000
noncomputable def cczGadgetOp000 : Matrix (Fin 64) (Fin 64) ℂ
definjectCCZ
noncomputable def injectCCZ : Matrix (Fin 64) (Fin 8) ℂ
defextractCCZ000
noncomputable def extractCCZ000 : Matrix (Fin 8) (Fin 64) ℂ
theoreminjectCCZ_apply
theorem injectCCZ_apply (ψ : StateVec 3) :
    injectCCZ * ψ = ψ ⊗ᵥ cczKet
theoremextractCCZ000_kron
theorem extractCCZ000_kron (d : StateVec 3) :
    extractCCZ000 * (d ⊗ᵥ (basisState 0 : StateVec 3)) = d
defcczKraus000
noncomputable def cczKraus000 : Matrix (Fin 8) (Fin 8) ℂ
defcczBorn000
noncomputable def cczBorn000 : ℂ
theoremcczKraus000_eq_smul_U
theorem cczKraus000_eq_smul_U :
    cczKraus000 = cczBorn000 • cczMat
*CCZ analogue (GAPS 1+3, 000 branch).** `Kraus_000 = c_000 • cczMat`.
defunitaryChannel
noncomputable def unitaryChannel {n : Nat} (U ρ : Matrix (Fin n) (Fin n) ℂ) :
    Matrix (Fin n) (Fin n) ℂ
The unitary channel of `U`: `ρ ↦ U·ρ·U†`.
theoremunitaryChannel_comp
theorem unitaryChannel_comp {n : Nat} (U₁ U₂ ρ : Matrix (Fin n) (Fin n) ℂ) :
    unitaryChannel U₂ (unitaryChannel U₁ ρ) = unitaryChannel (U₂ * U₁) ρ
*Channel composition.** Running the unitary channel of `U₁` then of `U₂` is the unitary channel of the product `U₂·U₁`. Iterating, a sequence of gadget channels (each `= unitaryChannel Uᵢ` by `tChannel_eq_unitaryChannel`) composes to `unitaryChannel (Uₙ·…·U₁)` — the program-level data channel of the compiled circuit.
theoremtChannel_eq_unitaryChannel'
theorem tChannel_eq_unitaryChannel' (ρ : Matrix (Fin 2) (Fin 2) ℂ) :
    tChannel ρ = unitaryChannel tMat ρ
The T gadget's data channel, against the general `unitaryChannel`.

FormalRV.PPM.GateToPPMResource

FormalRV/PPM/GateToPPMResource.lean
FormalRV.PPM.GateToPPMResource — weld the PPM resource count onto the SAME Gate IR term that carries a semantic-correctness proof. The honesty gap flagged by the semantic audit was: `ModExpToffoliCount`'s `16n³` is an ABSTRACT cost model, and the term fed to the PPM formula (`modmultBlock`) is an index-(0,1,2) repetition with NO semantics — so the count and the correctness ran on DIFFERENT terms. This file closes that gap at the layer where a verified Gate IR term exists: it compiles an arbitrary `Gate` (the IR the arithmetic circuits are PROVED correct in) to the PPM front-end and shows the PPM CCZ-magic / measurement counts equal the Gate's own Toffoli count. Applied to the verified Gidney adder, the result is a PPM resource count of the EXACT term proved to compute addition — genuinely end to end. ## What is and isn't end-to-end verified (honest) VERIFIED end to end (this file): the n-bit Gidney adder `gidney_adder_full_faithful_no_measurement (n+2)` — the SAME `Gate` term is proved to write the correct sum bits (`gidney_adder_full_faithful_no_measurement_target_correct`, no sorry) AND its PPM resource cost is derived from its proved Toffoli count (`tcount_… = 14(n+2)` ⇒ `2(n+2)` Toffolis ⇒ `2(n+2)` CCZ magic states). STILL a cost model (NOT welded): the full mod-exp `16n³` of `ModExpToffoliCount`. The verified modular multiplier `sqir_modmult_MCP_gate` exists and is semantically proved, but it has no Toffoli-count theorem yet, and no Gate term iterates it `2n` times into a verified modular exponentiation. So the 137-billion figure is an un-windowed upper bound, not a count read off a verified mod-exp circuit. This file welds the adder building block; the modmult / mod-exp welds remain future work. No `sorry`, no new `axiom`.
deftoffCount
def toffCount : Gate → Nat
  | .I => 0
  | .X _ => 0
  | .CX _ _ => 0
  | .CCX _ _ _ => 1
  | .seq g₁ g₂ => toffCount g₁ + toffCount g₂
Toffoli (CCX) count of a Gate IR circuit.
theoremtcount_eq_seven_mul_toffCount
theorem tcount_eq_seven_mul_toffCount (g : Gate) : tcount g = 7 * toffCount g
`tcount = 7 · toffCount`: each Toffoli is 7 T, everything else is 0.
defgateToHL
def gateToHL : Gate → List HLGate
  | .I => []
  | .X q => [.X q]
  | .CX c t => [.CNOT c t]
  | .CCX a b t => [.H t, .CCZ a b t, .H t]
  | .seq g₁ g₂ => gateToHL g₁ ++ gateToHL g₂
Compile a Gate IR circuit to the PPM front-end (`HLGate` list): every Toffoli becomes `H·CCZ·H`, `CX→CNOT`, `X→X`, `I` vanishes.
theoremcczMagic_sum_gateToHL
theorem cczMagic_sum_gateToHL (g : Gate) :
    ((gateToHL g).map gateCCZMagic).sum = toffCount g
theoremmeas_sum_gateToHL
theorem meas_sum_gateToHL (g : Gate) :
    ((gateToHL g).map gateMeas).sum = 3 * toffCount g
theoremnumCCZMagic_circuitToPPM_gateToHL
theorem numCCZMagic_circuitToPPM_gateToHL (na : Nat) (g : Gate) :
    numCCZMagic (circuitToPPM na (gateToHL g)) = toffCount g
PPM CCZ-magic count of a compiled Gate IR circuit = its Toffoli count.
theoremnumMeas_circuitToPPM_gateToHL
theorem numMeas_circuitToPPM_gateToHL (na : Nat) (g : Gate) :
    numMeas (circuitToPPM na (gateToHL g)) = 3 * toffCount g
PPM Pauli-measurement count of a compiled Gate IR circuit = `3 ×` its Toffoli count.
theoremtoffCount_gidney_adder
theorem toffCount_gidney_adder (n : Nat) :
    toffCount (gidney_adder_full_faithful_no_measurement (n + 2)) = 2 * (n + 2)
Toffoli count of the verified Gidney adder = `2(n+2)`, derived from its proved T-count `14(n+2)` (`tcount_gidney_adder_full_faithful_no_measurement`) via `7 T`/Toffoli.
theoremverified_adder_ppm_CCZMagic
theorem verified_adder_ppm_CCZMagic (na n : Nat) :
    numCCZMagic (circuitToPPM na (gateToHL (gidney_adder_full_faithful_no_measurement (n + 2))))
      = 2 * (n + 2)
PPM CCZ-magic states to teleport-compile the verified adder = `2(n+2)`.
theoremverified_adder_ppm_Meas
theorem verified_adder_ppm_Meas (na n : Nat) :
    numMeas (circuitToPPM na (gateToHL (gidney_adder_full_faithful_no_measurement (n + 2))))
      = 6 * (n + 2)
PPM Pauli measurements to teleport-compile the verified adder = `6(n+2)`.
theoremverified_adder_end_to_end
theorem verified_adder_end_to_end
    (n a b : Nat) (hn : 1 < n + 2) (ha : a < 2 ^ (n + 2)) (hb : b < 2 ^ (n + 2)) :
    (∀ i, i < n + 2 →
        Gate.applyNat (gidney_adder_full_faithful_no_measurement (n + 2))
          (adder_input_F (n + 2) a b) (target_idx i)
        = adder_sum_bit_classical a b i)
    ∧ numCCZMagic (circuitToPPM 0
          (gateToHL (gidney_adder_full_faithful_no_measurement (n + 2)))) = 2 * (n + 2)
    ∧ numMeas (circuitToPPM 0
          (gateToHL (gidney_adder_full_faithful_no_measurement (n + 2)))) = 6 * (n + 2)
*END-TO-END SEMANTICALLY-VERIFIED PPM RESOURCE COUNT (adder).** For the verified `n`-bit (`n ≥ 2`) Gidney adder, ONE Gate IR term simultaneously (a) computes the correct sum bits on the standard two-operand encoding, and (b) has PPM resource cost `2(n+2)` CCZ magic states + `6(n+2)` Z-basis measurements. Both conjuncts are about the SAME `gidney_adder_full_faithful_no_measurement (n+2)`.

FormalRV.PPM.GidneyAND

FormalRV/PPM/GidneyAND.lean
FormalRV.BQCode.GidneyAND — Gidney's measurement-based logical AND construction (arXiv:1709.06648). This file formally encodes Gidney's measurement-based AND, which is the load-bearing optimization in qianxu Eq. E3 (q_A Toffolis per q_A-bit adder). Without this trick, our gate-faithful adder encoding (BQAlgo/RippleCarryAdder.lean) gives 14n T-gates per n-bit adder (= 2 Toffolis per bit: 1 forward + 1 explicit reverse). With this trick, the reverse contributes 0 Toffolis, dropping the count to 7n — qianxu's stated figure. Structure (per Gidney 2018): - **Forward**: a single CCX(ctrl, tgt, anc) computing `anc ← anc ⊕ (ctrl ∧ tgt)`. Cost: 1 Toffoli = 7 T-gates. - **Reverse**: a single Z-basis PPM measuring the AND-ancilla, followed by a classical-controlled CX (CX(ctrl, tgt) conditional on the measurement outcome being 1). Cost: 0 Toffolis (PPM and classical CX both contribute 0 T-gates). *The review closure** (Iter 25's 14n-vs-7n finding): - Without this trick: gate-explicit reverse = 1 CCX, total 2 CCX/bit - With this trick: PPM-based reverse = 0 CCX, total 1 CCX/bit - Factor of 2 = exactly the gap our Lean encoding flagged.
defGidneyAND_forward
def GidneyAND_forward (ctrl tgt anc : Nat) : Gate
Forward Gidney-AND: single Toffoli CCX(ctrl, tgt, anc) computing `anc ← (ctrl ∧ tgt)`. Cost: 1 Toffoli = 7 T-gates.
theoremtcount_GidneyAND_forward
theorem tcount_GidneyAND_forward (ctrl tgt anc : Nat) :
    tcount (GidneyAND_forward ctrl tgt anc) = 7
Forward cost = exactly 1 Toffoli = 7 T-gates.
theoremgcount_GidneyAND_forward
theorem gcount_GidneyAND_forward (ctrl tgt anc : Nat) :
    gcount (GidneyAND_forward ctrl tgt anc) = 1
Gate count of the forward Gidney-AND is 1 (just the CCX).
structureGidneyAND_reverse
structure GidneyAND_reverse
The reverse Gidney-AND structural primitive. Carries the PPM (always a Z on the AND-ancilla `anc`) plus the conditional CX target qubits `(ctrl_q, tgt_q)`. Semantics: PPM measures Z on `anc`; if outcome = 1, apply CX(ctrl_q, tgt_q).
defGidneyAND_reverse.ppm
def GidneyAND_reverse.ppm (r : GidneyAND_reverse) : PPM
The reverse Gidney-AND's PPM contribution: a single-qubit Z measurement on `measure_qubit`. Builds a PauliString of length `total_qubits` with Z at position `measure_qubit` and I elsewhere.
defGidneyAND_reverse_tcount
def GidneyAND_reverse_tcount (_r : GidneyAND_reverse) : Nat
*Toffoli count of the reverse Gidney-AND is 0**. The reverse path is just a PPM + a classical-controlled CX — neither contributes a CCX. This is **the formal expression of the Gidney 2018 measurement trick**, and the closure of Iter 25's review-gap finding at the structural level.
theoremGidneyAND_reverse_tcount_eq_zero
theorem GidneyAND_reverse_tcount_eq_zero (r : GidneyAND_reverse) :
    GidneyAND_reverse_tcount r = 0
defGidneyAND_cycle_tcount
def GidneyAND_cycle_tcount (ctrl tgt anc : Nat) (r : GidneyAND_reverse) : Nat
Total T-count of a complete Gidney-AND cycle (forward + reverse).
theoremGidneyAND_cycle_tcount_eq_seven
theorem GidneyAND_cycle_tcount_eq_seven
    (ctrl tgt anc : Nat) (r : GidneyAND_reverse) :
    GidneyAND_cycle_tcount ctrl tgt anc r = 7
*Cycle T-count = 7**: a complete Gidney-AND uses exactly 7 T-gates, matching qianxu Eq. E3's per-Toffoli figure. Compare to the gate- explicit 14 T-gates (2 CCX per bit) the review's Iter 25 finding flagged.
example(example)
example :
    let r : GidneyAND_reverse
Concrete instance: at qubits (0, 1, 2) with reverse measuring qubit 2, the cycle costs 7 T-gates.

FormalRV.PPM.LayeredPPMQECInterface

FormalRV/PPM/LayeredPPMQECInterface.lean
FormalRV.Framework.LayeredPPMQECInterface — the first clean interface connecting the PPM/QEC LOGICAL layer to the existing backend compressed-schedule certificate, without falsely identifying PPM with physical SysCalls. ## Architectural layering (top → bottom) Logical Shor / arithmetic correctness ↓ Logical circuit / Clifford+T ↓ PPM / lattice-surgery logical-measurement layer ↓ QEC gadget implementation: stabilizer rounds, decoder, Pauli frame ↓ Backend compressed SysCall schedule ↓ System resource/invariant certificate ## What is and is NOT inside the existing System layer The compressed-schedule strict certificate (closed in `FormalRV.Framework.CompressedRepeatSoundness`) is a backend resource/scheduling proof: it speaks about `List SysCall`, physical site claims, factory ports, decoder service times, slot capacities, ancilla freshness, and per-cycle invariants. It is NOT the PPM semantic layer. PPM and QEC live ABOVE the backend system layer. This file introduces the FIRST layered interface: `PPMSpec` — abstract logical-measurement spec. `QECGadgetSpec` — abstract QEC-gadget spec wrapping a `PPMSpec`. `PPMToSystemLoweringCertificate` — pairs a PPM/QEC semantic obligation (carried as a `Prop` placeholder) with a backend compressed-schedule strict certificate. `VerifiedBackendBlock` — a packaged backend block that satisfies the strict system bundle on its expansion. `VerifiedPPMBlock` — a packaged PPM/QEC block that EXPOSES (but does not yet prove) the semantic obligation AND inherits backend system-correctness from its `VerifiedBackendBlock`. `ShorResourceVerificationInterface` — a top-level skeleton for end-to-end Shor resource verification. ## Out of scope for this tick Parallel composition soundness for `.par`. Full PPM semantics proof (`semantic_ok` is a placeholder). QEC decoder correctness or syndrome consistency. Hardware-specific routing (neutral-atom moves, superconducting microwave control, ion-trap shuttling). Shor top-level theorem. Neutral-atom and superconducting backends will instantiate the backend `SystemModels` differently, but they share this interface.
abbrevLogicalQubitId
abbrev LogicalQubitId
Identifier for a logical qubit. Aligned with `LogicalQubitBinding.logical_id : Nat` in `CodedLayout.lean`.
abbrevLogicalPatchId
abbrev LogicalPatchId
Identifier for a logical-qubit patch (a `CodeBlockBinding` in the existing code, identified by its `block_id : Nat`).
abbrevPhysicalSiteId
abbrev PhysicalSiteId
Identifier for a physical site (atom / qubit / cell) in the backend. Aligned with the existing `physical_qubits : List Nat` convention.
abbrevDecoderId
abbrev DecoderId
Identifier for a decoder instance. No existing decoder structure; a future tick can refine this to a `DecoderSpec`.
abbrevFactoryPortId
abbrev FactoryPortId
Identifier for a factory-output port. Aligned with the existing `RequestMagicState`-zone convention.
structurePPMSpec
structure PPMSpec
Abstract specification of a logical Pauli measurement (PPM) block. `measuredPauliKind` reuses the existing `Architecture.PauliKind` (I/X/Y/Z); a future tick can extend to a full `PauliString`-product measurement via `JointPauliMeasurementClaim` from `MultiQubitPPM.lean`.
structureQECGadgetSpec
structure QECGadgetSpec
Abstract specification of a QEC gadget implementing a `PPMSpec`. Wraps the existing L3 `PPMGadget` (operator-weight + `tau_s` cycle cost) and the existing L4 `QECCode` (parity-check matrices + `[[n, k, d]]` parameters), so consumers downstream of this interface can pull engineering cost / code parameters directly from the standard structures.
defPPMSpec.ofPauliMeasurementClaim
def PPMSpec.ofPauliMeasurementClaim
    (claim : PauliMeasurementClaim)
    (rounds distance : Nat) : PPMSpec
defQECGadgetSpec.ofPPMGadget
def QECGadgetSpec.ofPPMGadget
    (ppm : PPMSpec) (gadget : PPMGadget)
    (syndromeRounds : Nat) (decoder : DecoderId)
    (usesPauliFrame : Bool) : QECGadgetSpec
Adapter from the existing L3 `PPMGadget` + an in-flight `PPMSpec` into a `QECGadgetSpec`. Hardware-generic `decoder` and `usesPauliFrame` are supplied by the caller.
structurePPMToSystemLoweringCertificate
structure PPMToSystemLoweringCertificate
    (models : SystemModels)
structureVerifiedBackendBlock
structure VerifiedBackendBlock (models : SystemModels)
theoremVerifiedBackendBlock.strict_invariants_ok
theorem VerifiedBackendBlock.strict_invariants_ok
    (models : SystemModels) (b : VerifiedBackendBlock models) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        models.arch
        models.opCap
        models.slotCap
        models.ancillaModel
        b.schedule.expand
        models.t_react_us
        models.window_us
        models.max_per_window = true
A `VerifiedBackendBlock` satisfies the strict invariant bundle on its expanded schedule. Pure projection from `compressed_schedule_strict_soundness`.
structureVerifiedPPMBlock
structure VerifiedPPMBlock (models : SystemModels)
theoremVerifiedPPMBlock.system_invariants_ok
theorem VerifiedPPMBlock.system_invariants_ok
    (models : SystemModels) (b : VerifiedPPMBlock models) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        models.arch
        models.opCap
        models.slotCap
        models.ancillaModel
        b.backend.schedule.expand
        models.t_react_us
        models.window_us
        models.max_per_window = true
System-invariant projection: a `VerifiedPPMBlock` inherits backend system-correctness from its `VerifiedBackendBlock`. This theorem does NOT prove PPM/QEC semantic correctness — it merely projects the already-proved backend resource safety. Semantic correctness lives in `semantic_ok` and must be proved separately when refined to a concrete statement.
structureShorResourceVerificationInterface
structure ShorResourceVerificationInterface
    (models : SystemModels)
theoremShorResourceVerificationInterface.system_invariants_ok
theorem ShorResourceVerificationInterface.system_invariants_ok
    (models : SystemModels)
    (s : ShorResourceVerificationInterface models) :
    all_invariants_strict_with_slot_capacity_and_freshness_ok
        models.arch
        models.opCap
        models.slotCap
        models.ancillaModel
        s.schedule.expand
        models.t_react_us
        models.window_us
        models.max_per_window = true
The backend system-resource bundle holds on a `ShorResourceVerificationInterface`'s schedule. Same projection as `VerifiedBackendBlock.strict_invariants_ok`. This theorem does NOT prove logical-Shor correctness — it only projects backend resource safety.

FormalRV.PPM.LogicalState

FormalRV/PPM/LogicalState.lean
FormalRV.BQCode.LogicalState — operational infrastructure stub for Phase B emergent-action theorem. Per Iter 144 reflection: define LogicalState_4_2_2_pair as the type for "a quantum state in the +1 eigenspace of all 4 extended stabilizers of the 2-patch [[4,2,2]] system". This is step 1 of the 4-step infrastructure build-up (Iter 145-148) for the operational emergent-action theorem. *Status**: stub only. The structural commitments are real, but the underlying matrix-level semantics are intentionally postponed to future iters (146-147 add MeasurementOutcome + apply_PPM + apply_surgery_with_corrections).
defPauli.toMatrix
def Pauli.toMatrix : Pauli → Matrix (Fin 2) (Fin 2) ℂ
  | .I => !![1, 0; 0, 1]
  | .X => !![0, 1; 1, 0]
  | .Y => !![0, -Complex.I; Complex.I, 0]
  | .Z => !![1, 0; 0, -1]
Single-qubit Pauli matrix interpretation in `Matrix (Fin 2) (Fin 2) ℂ`.
example(example)
example : Pauli.toMatrix .I = !![(1:ℂ), 0; 0, 1]
*Structural sanity** for I: matrix is the 2×2 identity.
example(example)
example : (Pauli.toMatrix .X) 0 1 = 1
*Structural sanity** for X at index (0,1): the bit-flip matrix has 1 at off-diagonal positions.
example(example)
example : (Pauli.toMatrix .X) 1 0 = 1
*Structural sanity** for X at index (1,0).
example(example)
example :
    (Pauli.toMatrix .Z) 0 0 = 1
    ∧ (Pauli.toMatrix .Z) 1 1 = -1
*Structural sanity** for Z at diagonal.
example(example)
example :
    (Pauli.toMatrix .Y) 0 1 = -Complex.I
    ∧ (Pauli.toMatrix .Y) 1 0 = Complex.I
*Structural sanity** for Y at off-diagonal entries.
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .X) 0 0 = 1
*X * X = I at entry (0,0)**: matrix product diagonal entry. Verifies the bit-flip-squared identity.
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .X) 1 1 = 1
*X * X = I at entry (1,1)**: matrix product diagonal entry.
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .X) 0 1 = 0
*X * X = I at entry (0,1)**: off-diagonal vanishes.
example(example)
example : (Pauli.toMatrix .Z * Pauli.toMatrix .Z) 0 0 = 1
*Z * Z = I at entry (0,0)**: diagonal-squared.
example(example)
example : (Pauli.toMatrix .Z * Pauli.toMatrix .Z) 1 1 = 1
*Z * Z = I at entry (1,1)**: (-1)² = 1.
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .Z) 0 1 = -1
*X * Z at entry (0,1)**: bit-flip composed with phase-flip yields -1 on the upper-right. (Inductive `Pauli.mul .X .Z = (.negI, .Y)`, and `-i · Y_{0,1} = -i · -i = -1`. Consistent.)
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .Z) 1 0 = 1
*X * Z at entry (1,0)**: yields 1. (Inductive: negI · Y_{1,0} = -i · i = 1.)
example(example)
example : (Pauli.toMatrix .Z * Pauli.toMatrix .X) 0 1 = 1
*Z * X at entry (0,1)**: opposite ordering yields +1 (inductive `Pauli.mul .Z .X = (.posI, .Y)`, posI · Y_{0,1} = i · -i = 1). This confirms the anticommutation X·Z = -(Z·X) at the matrix level.
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .Y) 0 0 = 1
*Y * Y = I at diagonal (0,0)**: Pauli involution `Y² = I`. Direct entry check via matrix-mul + Fin sum. Inductive: `Pauli.mul .Y .Y = (.pos, .I)`. Both forms agree at (0,0): both give 1.
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .Y) 1 1 = 1
*Y * Y = I at diagonal (1,1)**. Computed: `(i · -i) + (0 · 0) = 1`. Confirms full diagonal of Y² = I.
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .Y) 0 1 = 0
*Y * Y = I at off-diagonal (0,1)**: vanishes (involution requires zero off-diagonal).
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .X) 0 0 = -Complex.I
*Y * X at entry (0,0)**: inductive `Pauli.mul .Y .X = (.negI, .Z)`, so `(.negI · Z_{0,0}) = (-i · 1) = -i`. Matrix product: `Y_{00}·X_{00} + Y_{01}·X_{10}` = `0·0 + (-i)·1` = `-i`. ✓
example(example)
example : (Pauli.toMatrix .X * Pauli.toMatrix .Y) 0 0 = Complex.I
*X * Y at entry (0,0)**: inductive `Pauli.mul .X .Y = (.posI, .Z)`, so `(.posI · Z_{0,0}) = (i · 1) = i`. Confirms opposite-ordering sign flip vs Y·X (anticommutation of X with Y).
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .Z) 0 0 = 0
*Y * Z at entry (0,0)**: inductive `Pauli.mul .Y .Z = (.posI, .X)`, so `(.posI · X_{0,0}) = (i · 0) = 0`. Matrix: `Y_{00}·Z_{00} + Y_{01}·Z_{10}` = `0·1 + (-i)·0` = `0`. ✓
example(example)
example : (Pauli.toMatrix .Y * Pauli.toMatrix .Z) 0 1 = Complex.I
*Y * Z at entry (0,1)**: inductive `Pauli.mul .Y .Z = (.posI, .X)`, so `(.posI · X_{0,1}) = (i · 1) = i`. Matrix: `Y_{00}·Z_{01} + Y_{01}·Z_{11}` = `0·0 + (-i)·(-1)` = `i`. ✓ Both forms agree on the Y·Z = iX identity.
defPauliString.toMatrix
noncomputable def PauliString.toMatrix : (P : PauliString) →
    Matrix (Fin (2 ^ P.length)) (Fin (2 ^ P.length)) ℂ
  | [] => 1
  | p :: ps =>
    Matrix.reindex finProdFinEquiv finProdFinEquiv
      (Matrix.kroneckerMap (· * ·) (PauliString.toMatrix ps) p.toMatrix)
*Multi-qubit Pauli string as matrix** (Iter 274, 2026-05-14): a `Matrix (Fin (2^n)) (Fin (2^n)) ℂ` representing the iterated Kronecker product of single-qubit Pauli matrices. *Convention**: `(p :: ps).toMatrix = ps.toMatrix ⊗ p.toMatrix` (qubit at list-position 0 is the LEAST-significant tensor factor — appears on the RIGHT). This is non-standard physics convention, but it lets the dependent-type plumbing close cleanly without casts because `Nat.pow_succ` reduces `2^(n+1) = 2^n * 2` (right multiplication). The matrix-level semantics are well-defined either way; downstream operational claims compose with this convention. Foundation for the operational tightening of `apply_PPM` (currently a `rfl`-placeholder identity on `LogicalState_4_2_2_pair`).
theoremPauliString.toMatrix_nil
theorem PauliString.toMatrix_nil :
    PauliString.toMatrix [] = (1 : Matrix (Fin 1) (Fin 1) ℂ)
*Empty Pauli string is the 1×1 identity matrix.**
theoremPauliString.toMatrix_cons
theorem PauliString.toMatrix_cons (p : Pauli) (ps : PauliString) :
    PauliString.toMatrix (p :: ps)
      = Matrix.reindex finProdFinEquiv finProdFinEquiv
          (Matrix.kroneckerMap (· * ·) (PauliString.toMatrix ps) p.toMatrix)
*Cons unfolds via Kronecker + reindex** — the structural recursion equation, useful for downstream proofs that need to step into the recursion.
theoremPauli.toMatrix_I_eq_one
theorem Pauli.toMatrix_I_eq_one :
    Pauli.toMatrix Pauli.I = (1 : Matrix (Fin 2) (Fin 2) ℂ)
*Pauli.I as 2×2 matrix is the identity** (Iter 277, 2026-05-14). Bridges the `Pauli.I` enum constructor to Mathlib's `(1 : Matrix (Fin 2) (Fin 2) ℂ)`. Useful for downstream proofs that need to fold strings of all-`Pauli.I` into the n-qubit identity.
theoremPauliString.toMatrix_replicate_I
theorem PauliString.toMatrix_replicate_I (n : Nat) :
    PauliString.toMatrix (List.replicate n Pauli.I) = 1
*All-`Pauli.I` PauliString as matrix is the identity** (Iter 278). `PauliString.toMatrix (List.replicate n .I) = 1`, where the `1`'s type is the implied `Matrix (Fin (2^(List.replicate n .I).length)) ... ℂ`. Proof by induction on `n`, using: - `_nil` (Iter 275) for the base. - `_cons` (Iter 275) + IH + `Pauli.toMatrix_I_eq_one` (Iter 277). - `Matrix.kroneckerMap_one_one`: kroneckerMap of two identities is identity (for multiplicative `f` with zero/one preservation). - `Matrix.submatrix_one`: submatrix of identity by an injective reindex is identity.
theoremPauli.toMatrix_mul_self
theorem Pauli.toMatrix_mul_self (p : Pauli) :
    Pauli.toMatrix p * Pauli.toMatrix p = (1 : Matrix (Fin 2) (Fin 2) ℂ)
*Each Pauli matrix is an involution** (Iter 279): `P · P = I` for every `p : Pauli`. Direct case analysis with `Matrix.mul_apply` + `Fin.sum_univ_two` to expand the 2×2 product and `simp` for the complex arithmetic (`Complex.I * Complex.I = -1`, etc.). This is the load-bearing identity for projection-onto-±1-eigenspace reasoning downstream: `(I ± P)/2` is idempotent precisely because `P² = I`.
theoremPauliString.toMatrix_mul_self
theorem PauliString.toMatrix_mul_self (P : PauliString) :
    P.toMatrix * P.toMatrix = 1
*PauliString is matrix-level involution** (Iter 280, 2026-05-14): `P.toMatrix * P.toMatrix = 1` for any `P : PauliString`. Lifts the single-qubit Pauli involution (Iter 279) to n qubits via the `Matrix.kroneckerMap` recursion. *Why it matters**: the PPM projector `(I ± P)/2` is idempotent precisely because `P² = I`. With this lemma, the operational tightening of `apply_PPM` to a real ±1-eigenspace projection becomes structurally possible — the algebraic identity that makes projection well-defined is now available at the matrix level for arbitrary PauliStrings. *Proof structure** (induction on the list): - Base `nil`: `toMatrix [] = 1`, so `1 * 1 = 1` by `one_mul`. - Step `cons p ps`: unfold via `toMatrix_cons` (Iter 275) and `reindex_apply`, then: - `Matrix.submatrix_mul_equiv` to combine the two submatrix products into a single submatrix of the inner product. - `← Matrix.mul_kronecker_mul` (Mathlib): kron mul kron is kron of muls. - IH (collapses ps factor to 1) and `Pauli.toMatrix_mul_self` (collapses p factor to 1). - `Matrix.kroneckerMap_one_one`: kron(1, 1) = 1. - `Matrix.submatrix_one`: submatrix of 1 by an injective reindex is 1. *Key trick** (the `show` line): the recursive definition of `toMatrix (p :: ps)` has natural type `Matrix (Fin (2^ps.length * 2)) ...`, but the goal type uses `Matrix (Fin (2^(p :: ps).length)) ...`. These are defeq but Lean's `rw` matcher doesn't unfold the `Nat.pow` reduction automatically. The explicit `show` forces the goal into the `reindex finProdFinEquiv finProdFinEquiv (kroneckerMap ...)` form where the subsequent rewrites can fire.
theoremPauli.toMatrix_comm_of_commutes
theorem Pauli.toMatrix_comm_of_commutes (p q : Pauli)
    (h : commutes p q = true) :
    Pauli.toMatrix p * Pauli.toMatrix q
      = Pauli.toMatrix q * Pauli.toMatrix p
*Single-qubit Pauli commutation at the matrix level** (Iter 281): if `commutes p q = true` (Pauli-algebra commutation), then the matrix products commute: `p.toMatrix * q.toMatrix = q.toMatrix * p.toMatrix`. Proof by 16-case analysis (`cases p <;> cases q`). For the 10 commuting cases (same Pauli, or one of them is `.I`), the 2×2 matrix-element equality discharges via `simp` + the standard `Matrix.mul_apply` / `Fin.sum_univ_two` expansion. For the 6 anti-commuting cases (X/Y, X/Z, Y/Z and their swaps), the hypothesis `h : commutes p q = true` reduces to `False` under `simp [commutes, Pauli.mul]` and closes by contradiction. *Why it matters**: this is the matrix-level instantiation of the Pauli-algebra commutation predicate (PPM.lean line 109). It is the building block for lifting `PauliString.commutes` (the abstract commutation predicate on n-qubit Pauli strings) to a real matrix-product commutation — needed for proving that two PPMs of mutually commuting Pauli strings can be performed in either order with the same operational effect.
theoremPauliString.toMatrix_projector_idem_aux
theorem PauliString.toMatrix_projector_idem_aux (P : PauliString) :
    (1 + P.toMatrix) * (1 + P.toMatrix) = 2 • (1 + P.toMatrix)
*PPM projector idempotency (algebraic form, multi-qubit)** (Iter 282). For any PauliString `P`, the unnormalized projector `1 + P.toMatrix` onto the `+1` eigenspace satisfies `(1 + P) * (1 + P) = 2 • (1 + P)`. *Algebraic content**: `(1 + P)² = 1 + 2P + P² = 1 + 2P + 1 = 2(1 + P)`. The crucial step `P² = 1` is exactly `PauliString.toMatrix_mul_self` (Iter 280); the rest is ring distribution + abelian group manipulation. *Why it matters**: dividing both sides by `4` (over `ℂ`) gives `((1 + P)/2)² = (1 + P)/2`, the standard idempotency identity of the normalized PPM `+1`-eigenspace projector. This is the last algebraic prerequisite before `apply_PPM` can be tightened from its `rfl` placeholder to a real projection operator. The unnormalized form (with `2 •`) avoids the inverse / division machinery and stays inside the commutative-monoid algebra.
theoremPauliString.toMatrix_projector_idem_aux_minus
theorem PauliString.toMatrix_projector_idem_aux_minus (P : PauliString) :
    (1 - P.toMatrix) * (1 - P.toMatrix) = 2 • (1 - P.toMatrix)
*PPM projector idempotency (algebraic form, `-1` eigenspace)** (Iter 283). Sign-flipped twin of Iter 282: for any PauliString `P`, the unnormalized `-1`-eigenspace projector `1 - P.toMatrix` satisfies `(1 - P) * (1 - P) = 2 • (1 - P)`. *Algebraic content**: `(1 - P)² = 1·1 - 1·P - P·1 + P·P = 1 - P - P + 1 = 2(1 - P)`. Identical proof shape to Iter 282, swap `add_mul` → `sub_mul`, `mul_add` → `mul_sub`. *Why it matters**: dividing both sides by 4 over `ℂ` gives the normalized identity `((1 - P)/2)² = (1 - P)/2`, the idempotency of the `-1`-eigenspace projector. With Iter 282 and this lemma together, both PPM measurement outcomes are characterized by well-defined projectors. The next algebraic step is orthogonality (`(1+P)(1-P) = 0`) and resolution of identity (`(1+P) + (1-P) = 2 • 1`).
theoremPauliString.toMatrix_projector_orthogonality
theorem PauliString.toMatrix_projector_orthogonality (P : PauliString) :
    (1 + P.toMatrix) * (1 - P.toMatrix) = 0
*PPM projector orthogonality** (Iter 284). For any PauliString `P`, the `+1` and `-1` eigenspace projectors annihilate each other: `(1 + P) * (1 - P) = 0` (and by an identical proof `(1 - P) * (1 + P) = 0`). *Algebraic content**: `(1 + P)(1 - P) = 1·1 - 1·P + P·1 - P·P = 1 - P + P - 1 = 0`. The crucial cancellation is `P² = 1` (Iter 280), which sets the `-P²` cross term equal to `-1`, cancelling the leading `+1`. The remaining `-P + P` cancels by additive inverse. *Why it matters**: orthogonality is the second of three characterizing identities of a projection-valued measure (PVM): 1. Idempotency (Iter 282, 283). ✓ 2. **Orthogonality (this lemma).** ✓ 3. Resolution of identity (Iter 285 plan). Together they certify that `Π₊` and `Π₋` form a complete PVM, so a PPM measurement decomposes the state space cleanly into two orthogonal eigenspaces — the operational meaning of "Pauli measurement".
theoremPauliString.toMatrix_projector_resolution
theorem PauliString.toMatrix_projector_resolution (P : PauliString) :
    (1 + P.toMatrix) + (1 - P.toMatrix)
      = (2 • 1 : Matrix (Fin (2^P.length)) (Fin (2^P.length)) ℂ)
*PPM resolution of identity** (Iter 285). For any PauliString `P`, the `+1` and `-1` unnormalized projectors sum to twice the identity matrix: `(1 + P) + (1 - P) = 2 • 1`. Dividing by 2 over `ℂ` gives the standard resolution-of-identity `Π₊ + Π₋ = (1 + P)/2 + (1 - P)/2 = 1`. *Algebraic content**: `(1 + P) + (1 - P) = 1 + P + 1 - P = 2`. This identity does NOT depend on `P² = 1`; it is a pure abelian-group identity, so the proof is `rw [two_smul]; abel`. *Why it matters**: this is the third (and last) of the three PVM characterizing identities: 1. Idempotency `Π_±² = Π_±` (Iter 282, 283). ✓ 2. Orthogonality `Π₊ · Π₋ = 0` (Iter 284). ✓ 3. **Resolution of identity `Π₊ + Π₋ = 1` (this lemma).** ✓ With all three in hand, `{Π₊, Π₋}` is a complete PVM in the classical operator-algebra sense. A PPM measurement of `P` is now a well-defined operational primitive: decompose the state space into `Π₊ |ψ⟩ ⊕ Π₋ |ψ⟩` and return the outcome with probability proportional to the squared norm of the respective component. The next step is to wire these matrix identities into the operational `apply_PPM` definition (Iter 286+).
inductivePointwisePauliCommutes
inductive PointwisePauliCommutes : PauliString → PauliString → Prop
  | nil : PointwisePauliCommutes [] []
  | cons : ∀ {p q : Pauli} {ps qs : PauliString},
      Pauli.commutes p q = true → PointwisePauliCommutes ps qs →
      PointwisePauliCommutes (p :: ps) (q :: qs)
*Pointwise commutation predicate** (Iter 286). An inductive propositional predicate stating that two PauliStrings `P` and `Q` have equal length AND commute position-by-position in the underlying Pauli algebra. *Why an inductive predicate** (rather than `∀ i, commutes (P.get i) (Q.get i) = true`): the inductive form lets us pattern-match on it in proofs, recovering both the same-length and the head-commutes hypotheses simultaneously. The List-quantified form would require carrying a separate `P.length = Q.length` hypothesis through every step.
theoremPointwisePauliCommutes.length_eq
theorem PointwisePauliCommutes.length_eq :
    ∀ {P Q : PauliString}, PointwisePauliCommutes P Q → P.length = Q.length
  | _, _, .nil => rfl
  | _, _, .cons _ h => congrArg (· + 1) (PointwisePauliCommutes.length_eq h)
*Equal-length consequence of pointwise commutation** (Iter 286). If `P` and `Q` commute pointwise (as PauliStrings), they must have the same length. Proof by induction on the predicate: `nil` matches `[]` against `[]`; `cons` adds one to each side, preserving equality. Useful both as an invariant of `PointwisePauliCommutes` and as the cast needed to type-check `P.toMatrix * Q.toMatrix` (both matrices live in `Matrix (Fin (2^length)) ...`, so multiplication requires equal-length).
theoremPauli.commutes_comm
theorem Pauli.commutes_comm (p q : Pauli) :
    Pauli.commutes p q = Pauli.commutes q p
*Single-Pauli commutation is symmetric** (Iter 287). `commutes p q = commutes q p` for any Paulis `p, q`. Proved by 16-case `decide`.
theoremPointwisePauliCommutes.self
theorem PointwisePauliCommutes.self :
    ∀ (P : PauliString), PointwisePauliCommutes P P
  | [] => .nil
  | (p :: ps) =>
      .cons (Pauli.commutes_self p) (PointwisePauliCommutes.self ps)
*Every PauliString commutes pointwise with itself** (Iter 287). Reflexivity of `PointwisePauliCommutes`: any PauliString trivially commutes with itself position-by-position because each Pauli commutes with itself (`Pauli.commutes_self` in PPM.lean).
theoremPointwisePauliCommutes.symm
theorem PointwisePauliCommutes.symm :
    ∀ {P Q : PauliString}, PointwisePauliCommutes P Q →
                            PointwisePauliCommutes Q P
  | _, _, .nil => .nil
  | _, _, .cons hpq h =>
      .cons (by rw [Pauli.commutes_comm]; exact hpq)
            (PointwisePauliCommutes.symm h)
*Pointwise commutation is symmetric** (Iter 287). If `P` commutes with `Q` pointwise, then `Q` commutes with `P` pointwise. Proven by recursion on the predicate; uses `Pauli.commutes_comm` for the head and the IH for the tail.
theoremPointwisePauliCommutes.replicate_I_left
theorem PointwisePauliCommutes.replicate_I_left :
    ∀ (Q : PauliString),
    PointwisePauliCommutes (List.replicate Q.length Pauli.I) Q
  | [] => by exact PointwisePauliCommutes.nil
  | (q :: qs) =>
*All-identity Pauli string commutes with anything (left)** (Iter 289). If `P` is `List.replicate Q.length Pauli.I` (all-`I` of the right length), it commutes pointwise with `Q`. Direct consequence of `Pauli.commutes_I_left` (PPM.lean line 128) applied at every position.
theoremPointwisePauliCommutes.replicate_I_right
theorem PointwisePauliCommutes.replicate_I_right :
    ∀ (P : PauliString),
    PointwisePauliCommutes P (List.replicate P.length Pauli.I)
  | [] => by exact PointwisePauliCommutes.nil
  | (p :: ps) =>
*All-identity Pauli string commutes with anything (right)** (Iter 289). Symmetric twin of `replicate_I_left`: any `P` commutes pointwise with `List.replicate P.length Pauli.I`. Useful when one logical operator acts trivially on a sub-register.
theoremPointwisePauliCommutes.append
theorem PointwisePauliCommutes.append :
    ∀ {P₁ Q₁ P₂ Q₂ : PauliString},
    PointwisePauliCommutes P₁ Q₁ → PointwisePauliCommutes P₂ Q₂ →
    PointwisePauliCommutes (P₁ ++ P₂) (Q₁ ++ Q₂)
  | _, _, _, _, .nil, h₂ => h₂
  | _, _, _, _, .cons hpq h₁, h₂ =>
*Pointwise commutation composes via append** (Iter 290). Concatenation of two pointwise-commuting pairs is pointwise-commuting: `P₁ ~ Q₁ → P₂ ~ Q₂ → (P₁ ++ P₂) ~ (Q₁ ++ Q₂)`. *Why it matters**: surgery schedules build PauliString stabilizers by concatenating per-patch contributions. With `append`, commutation of full stabilizers reduces to commutation of per-patch pieces. The [[4,2,2]] CNOT surgery's `Code4Code4_XXXX_L` = `[X, X, X, X] ++ List.replicate 4 .I` commutes pointwise with `Code4Code4_ZZZZ_R` = `List.replicate 4 .I ++ [Z, Z, Z, Z]` because each half-pair is either same-pattern (any string vs all-I gives commutation by `replicate_I_*`) or trivially equal.
theoremPointwisePauliCommutes.disjoint_left_right
theorem PointwisePauliCommutes.disjoint_left_right (P Q : PauliString) :
    PointwisePauliCommutes
      (P ++ List.replicate Q.length Pauli.I)
      (List.replicate P.length Pauli.I ++ Q)
*Disjoint-support commutation pattern** (Iter 290). The canonical instance for surgery schedules: an operator `P` on a left sub-register (with identity padding on the right) commutes pointwise with the "swapped" pattern (identity padding on the left, operator `Q` on the right). Direct corollary of `append` + `replicate_I_*`. Concrete use case: `Code4Code4` 2-patch surgery has stabilizers like `XXXX_L = XXXX ++ IIII` (acting on qubits 0-3, identity on 4-7) and `ZZZZ_R = IIII ++ ZZZZ` (acting on qubits 4-7, identity on 0-3). `disjoint_left_right [X,X,X,X] [Z,Z,Z,Z]` directly produces the pointwise-commutation witness.
theoremPauliString.commutes_of_pointwise
theorem PauliString.commutes_of_pointwise :
    ∀ {P Q : PauliString}, PointwisePauliCommutes P Q →
    PauliString.commutes P Q = true
  | _, _, .nil => rfl
  | _, _, .cons hpq h =>
*Pointwise commutation implies abstract Pauli-string commutation** (Iter 291). The `PointwisePauliCommutes` predicate is a sufficient condition for the abstract symplectic `PauliString.commutes` (PPM.lean line 271): if every position commutes pointwise, then the parity of anti-commuting positions is zero (trivially even). *Note**: the converse is FALSE — `PauliString.commutes` is the weaker parity condition (even number of anti-commuting positions suffices), so two strings can `commutes` without pointwise-commuting. Example: `[X, Y]` and `[Y, X]` both anti-commute pointwise (2 anti-commuting positions, even total), so they `commutes` but NOT `PointwisePauliCommutes`. *Why this lemma**: bridges our predicate-level abstraction to the pre-existing `PauliString.commutes` symplectic predicate already used in PPM.lean's stabilizer-code proofs. Now any consumer that has a `PointwisePauliCommutes P Q` witness can also conclude `PauliString.commutes P Q = true`.
theoremCode4Code4_XXXX_L_pointwise_commutes_ZZZZ_R
theorem Code4Code4_XXXX_L_pointwise_commutes_ZZZZ_R :
    PointwisePauliCommutes Code4Code4_XXXX_L Code4Code4_ZZZZ_R
*[[4,2,2]] left/right disjoint-patch stabilizers commute pointwise** (Iter 292). Concrete application of the `disjoint_left_right` pattern to the 2-patch [[4,2,2]] system's stabilizer pair `XXXX_L` (acts on qubits 0-3) and `ZZZZ_R` (acts on qubits 4-7). Decomposition: `Code4Code4_XXXX_L = [X, X, X, X] ++ List.replicate 4 Pauli.I` and `Code4Code4_ZZZZ_R = List.replicate 4 Pauli.I ++ [Z, Z, Z, Z]`. The two strings have disjoint Pauli support (one acts only on positions 0-3, the other only on 4-7), so every position has at least one identity, and pointwise commutation follows directly from `PointwisePauliCommutes.disjoint_left_right`. *Why this matters as an review deliverable**: this is the FIRST concrete application of the Iter 286-291 `PointwisePauliCommutes` abstraction layer to a paper-defined surgery stabilizer. With the pointwise witness in hand, `PauliString.commutes_of_pointwise` (Iter 291) immediately gives `PauliString.commutes Code4Code4_XXXX_L Code4Code4_ZZZZ_R = true`. This grounds the abstraction in the actual surgery schedule's correctness chain.
theoremCode4Code4_XXXX_L_pointwise_commutes_XXXX_R
theorem Code4Code4_XXXX_L_pointwise_commutes_XXXX_R :
    PointwisePauliCommutes Code4Code4_XXXX_L Code4Code4_XXXX_R
*[[4,2,2]] disjoint-patch: `XXXX_L` commutes with `XXXX_R`** (Iter 293). Same proof pattern as `XXXX_L_pointwise_commutes_ZZZZ_R` (Iter 292), with `[Z,Z,Z,Z]` swapped to `[X,X,X,X]` on the right-patch side.
theoremCode4Code4_ZZZZ_L_pointwise_commutes_XXXX_R
theorem Code4Code4_ZZZZ_L_pointwise_commutes_XXXX_R :
    PointwisePauliCommutes Code4Code4_ZZZZ_L Code4Code4_XXXX_R
*[[4,2,2]] disjoint-patch: `ZZZZ_L` commutes with `XXXX_R`** (Iter 293).
theoremCode4Code4_ZZZZ_L_pointwise_commutes_ZZZZ_R
theorem Code4Code4_ZZZZ_L_pointwise_commutes_ZZZZ_R :
    PointwisePauliCommutes Code4Code4_ZZZZ_L Code4Code4_ZZZZ_R
*[[4,2,2]] disjoint-patch: `ZZZZ_L` commutes with `ZZZZ_R`** (Iter 293). Final entry in the disjoint-patch quadrant of the [[4,2,2]] 4×4 stabilizer-commutation matrix.
lemmatoMatrix_cons_cast
private lemma toMatrix_cons_cast {q : Pauli} {qs ps : PauliString}
    (hsym : qs.length = ps.length) :
    (congrArg (· + 1) hsym ▸ PauliString.toMatrix (q :: qs)
      : Matrix (Fin (2^(ps.length + 1))) (Fin (2^(ps.length + 1))) ℂ)
      = Matrix.reindex finProdFinEquiv finProdFinEquiv
          (Matrix.kroneckerMap (· * ·)
            (hsym ▸ PauliString.toMatrix qs
              : Matrix (Fin (2^ps.length)) (Fin (2^ps.length)) ℂ)
            q.toMatrix)
*Helper for cast threading in cons-case** (added 2026-05-23). Pushes the outer length cast on `toMatrix (q :: qs)` through the `reindex finProdFinEquiv finProdFinEquiv (kron ...)` structure to expose an inner cast on `qs.toMatrix`. Proof: `subst` on the length equality (after `generalize`ing `ps.length` to a free Nat) makes both sides definitionally equal.
theoremPauliString.toMatrix_comm_of_pointwise
theorem PauliString.toMatrix_comm_of_pointwise :
    ∀ {P Q : PauliString} (h : PointwisePauliCommutes P Q),
      PauliString.toMatrix P *
          (h.length_eq.symm ▸ PauliString.toMatrix Q
            : Matrix (Fin (2^P.length)) _ ℂ)
        = (h.length_eq.symm ▸ PauliString.toMatrix Q
            : Matrix (Fin (2^P.length)) _ ℂ) * PauliString.toMatrix P
  | [], [], _ => by simp [PauliString.toMatrix]
  | (p :: ps), (q :: qs), .cons hpq h_tail =>
*PauliString commutation at the matrix level via pointwise** (Iter 286, **closed 2026-05-23**). If every position of `P` and `Q` commutes (and lengths match — both implied by `PointwisePauliCommutes P Q`), then the n-qubit matrices commute as operators. *Statement note**: the matrix product `P.toMatrix * Q.toMatrix` requires `P.length = Q.length` to type-check. The predicate enforces this, but Lean's elaborator doesn't see the equality until pattern-matching. We thread the `length_eq` cast explicitly via `h.length_eq.symm ▸ Q.toMatrix`, turning `Q.toMatrix`'s type from `Matrix (Fin (2^Q.length)) ...` into `Matrix (Fin (2^P.length)) ...`. After this cast, the multiplication type-checks. *Proof structure**: structural recursion on the predicate. - `nil` case: both toMatrix's are `(1 : Matrix (Fin 1) (Fin 1) ℂ)`, cast is identity, closes by `simp`. - `cons p q ps qs hpq h_tail` case: 1. Apply IH to get commutation on `ps`/`qs`. 2. Use `toMatrix_cons_cast` helper to push the outer cast (`(cons _ _).length_eq.symm`) inward to a cast on `qs.toMatrix`. 3. `simp only [Matrix.reindex_apply]` converts reindex to submatrix. 4. `submatrix_mul_equiv` (×2) combines factors under shared middle equiv. 5. `← Matrix.mul_kronecker_mul` (×2) factors kron of muls. 6. `IH` and `Pauli.toMatrix_comm_of_commutes` swap the inner factors. *Why it matters**: this is the general PauliString-level commutation lift. The PPM measurement-order independence theorem needs this. The pointwise specialization (every position commutes outright) sidesteps the parity argument required by full `PauliString.commutes` (PPM.lean line 271) but covers practically-important cases: - Disjoint-support stabilizers (`XXXX_L` and `XXXX_R` on qubits 0-3 and 4-7). - Stabilizer-with-identity commutation.
abbrevJointStateVector
abbrev JointStateVector
A 2^8 = 256-dimensional complex column vector. Concrete shape for the joint [[4,2,2]] ⊗ [[4,2,2]] 8-qubit system.
defin_Code4Code4_codespace
def in_Code4Code4_codespace (_v : JointStateVector) : Prop
*Placeholder predicate** for "vector is in the +1 eigenspace of all 4 extended stabilizers". Future iter 146 will tighten this to an actual matrix-action constraint once `PauliString.toMatrix` is available. For now it's abstract, accepting any vector.
structureLogicalState_4_2_2_pair
structure LogicalState_4_2_2_pair
*LogicalState of the 2-patch [[4,2,2]] joint system**: a 256-dim vector with a proof it lies in the joint codespace. The codespace itself has dimension 16 (4 logical qubits). Future iters will refine the `in_codespace` predicate.
example(example)
example (v : JointStateVector) : in_Code4Code4_codespace v
*Structural sanity**: the codespace predicate is currently trivially satisfied. This decide-witness confirms `True` holds, anchoring the stub at the right type.
defLogicalState_4_2_2_pair.mk_trivial
def LogicalState_4_2_2_pair.mk_trivial (v : JointStateVector) :
    LogicalState_4_2_2_pair
Constructor from a vector (using the trivial placeholder predicate). After Iter 146 tightens the predicate, callers must provide a real proof.
defCode4Code4_CNOT_L1L_R1_matrix
noncomputable def Code4Code4_CNOT_L1L_R1_matrix :
    Matrix (Fin (2^8)) (Fin (2^8)) ℂ
*Logical-CNOT unitary on the [[4,2,2]] 2-patch codespace** (Iter 295). The 256×256 complex matrix that implements the logical CNOT from `L1_left` (control) to `L1_right` (target). Built from: - `Z_L1 := Code4Code4_Z_L1_left.toMatrix` — logical Z on the left patch's L1 qubit, embedded in the 256-dim joint space. - `X_R1 := Code4Code4_X_L1_right.toMatrix` — logical X on the right patch's L1 qubit. Formula: `(1/2) · (I + Z_L1 + X_R1 − Z_L1 · X_R1)`. *Type-coercion note**: each PauliString in the 2-patch system has length 8 (e.g., `Code4Code4_Z_L1_left = [.Z, .I, .Z, .I, .I, .I, .I, .I]`), so `toMatrix` produces `Matrix (Fin (2 ^ 8)) (Fin (2 ^ 8)) ℂ`. The let-bindings carry explicit type annotations to force the coercion (`length` doesn't reduce to `8` automatically in all elaboration contexts).
defapply_logical_gate
noncomputable def apply_logical_gate (g : Framework.Gate)
    (s : LogicalState_4_2_2_pair) : LogicalState_4_2_2_pair
*Apply an abstract logical gate to a `LogicalState_4_2_2_pair`** (Iter 295). Pattern-matches on the `Gate` constructor. Currently only `Gate.CX 0 1` (logical CNOT from L1_left to L1_right) has a non-trivial action; all other gates return the input state unchanged. Future iters extend coverage to `Gate.X`, `Gate.CCX` (via magic-state injection at LP scale), and other gates from the `Gate` IR. *Review role**: this is the LEFT side of the bridge theorem `surgery_CNOT_implements_gate_CX`. The right side is the `apply_PPM_schedule + classical_pauli_feedback` on `Code4Code4_CNOT_surgery_schedule`. The bridge theorem (sub-deliverable 5 of Iter 294 goal refresh) is the load-bearing claim that these two sides agree on the codespace.
inductiveMeasurementOutcome
inductive MeasurementOutcome
  | plus    -- +1 eigenvalue
  | minus   -- -1 eigenvalue
  deriving DecidableEq, Repr
*Measurement outcome** of a single PPM: ±1 eigenvalue.
defMeasurementOutcome.toComplex
def MeasurementOutcome.toComplex : MeasurementOutcome → ℂ
  | .plus  => 1
  | .minus => -1
*Numerical eigenvalue** of a measurement outcome: `plus → 1`, `minus → -1`. Connects the inductive `MeasurementOutcome` to its Complex-number interpretation, needed for any future tightening of `apply_PPM` to its operational matrix definition (projector `(I + λ·P)/2` for eigenvalue `λ`).
defoutcome_product
def outcome_product : List MeasurementOutcome → ℂ
  | [] => 1
  | x :: xs => x.toComplex * outcome_product xs
*Cumulative outcome sign**: product of `toComplex` over a list of outcomes. Useful for tracking measurement-frame Pauli corrections — when the surgery's correction function consumes `n` outcomes, the cumulative sign decides whether an overall Pauli is applied vs. not.
example(example)
example : MeasurementOutcome.plus.toComplex = 1
*Structural sanity**: `plus.toComplex = 1`.
example(example)
example : MeasurementOutcome.minus.toComplex = -1
*Structural sanity**: `minus.toComplex = -1`.
example(example)
example : outcome_product [] = 1
*Outcome product empty list = 1** (multiplicative identity).
example(example)
example :
    outcome_product [.plus, .plus, .plus, .plus, .plus] = 1
*Outcome product on all-plus list = 1**. Five `plus` outcomes (matching the 5-PPM surgery schedule) yield product = 1.
example(example)
example :
    outcome_product [.plus, .minus, .plus, .plus, .plus] = -1
*Outcome product with one `minus` = -1**. Confirms a single minus outcome flips the cumulative sign — the structural foundation for measurement-frame Pauli corrections.
example(example)
example :
    outcome_product [.minus, .plus, .minus, .plus, .plus] = 1
*Outcome product with two `minus` = +1**. Even number of minus outcomes restores the positive cumulative sign.
defapply_PPM
def apply_PPM (s : LogicalState_4_2_2_pair) (_ppm : PPM) :
    MeasurementOutcome × LogicalState_4_2_2_pair
*Apply a PPM to a LogicalState**: produces a measurement outcome and a post-measurement state. Implementation requires `PauliString.toMatrix` (projection operators `(I ± P)/2`), which is sorried until a future tick adds that infrastructure. *Specification** (`TODO_apply_PPM_specification`): 1. When the PPM operator commutes with all 4 extended stabilizers of `Code4Code4`, the post-state remains in the codespace (preserves `in_codespace`). 2. The two outcomes correspond to the ±1 eigenprojectors of the PPM's measurement operator. 3. Outcome probabilities are determined by Born's rule on the input vector. For now: returns `(plus, trivial-state)` regardless of input — a placeholder that type-checks but has no operational content. Future iter 147+ tightens this.
defapply_PPM_projector
noncomputable def apply_PPM_projector
    (s : LogicalState_4_2_2_pair)
    (P : Matrix (Fin (2^8)) (Fin (2^8)) ℂ)
    (outcome : MeasurementOutcome) :
    LogicalState_4_2_2_pair
*Apply a PPM projector with given outcome** (Iter 296, 2026-05-14). Operational primitive for the PPM-arithmetic bridge: applies the `+1`- or `-1`-eigenspace projector of a Pauli measurement operator to the joint state vector. *Signature design**: takes an EXPLICIT `outcome` parameter rather than computing it from Born's rule. This decouples the projector application (deterministic matrix multiplication) from outcome selection (probabilistic, requires norm calculation). Downstream proofs enumerate over outcomes via pattern match; for the bridge theorem `surgery_CNOT_implements_gate_CX` (Iter 299 plan), the correction function makes the per-outcome state match the logical gate's action regardless of outcome. *Operator form** (from Iter 282-283 PVM characterization): - `outcome = .plus`: projector `(I + P)/2` - `outcome = .minus`: projector `(I - P)/2` *Type-coercion design**: takes the measurement matrix `P` as a pre-coerced `Matrix (Fin (2^8)) (Fin (2^8)) ℂ`. The caller is responsible for `ppm.measure.toMatrix` with explicit length-cast. This sidesteps the `PauliString.length` defeq issue in elaboration. Codespace preservation: when `P` commutes with all stabilizers, the projected state remains in the codespace. Currently `in_codespace` is the trivial `True` predicate; future tightening (Iter 298+) connects this lemma.
example(example)
example : (MeasurementOutcome.plus = MeasurementOutcome.minus) = False
*Structural sanity for outcomes**: `plus ≠ minus`. Provides a decidable inequality witness for downstream proofs.
example(example)
example (s : LogicalState_4_2_2_pair) (ppm : PPM) :
    let result
*Apply_PPM placeholder structural check**: applying a PPM to any logical state yields a result of type `MeasurementOutcome × LogicalState_4_2_2_pair`. Trivial type sanity at this stage of the infrastructure build-up.
defCode4Code4_CNOT_correction_fn
def Code4Code4_CNOT_correction_fn (_outcomes : List MeasurementOutcome) :
    PauliString
*Correction function** for the 5-PPM CNOT surgery: maps the 5 measurement outcomes (one per PPM in `Code4Code4_CNOT_surgery_schedule`) to the Pauli string that must be applied to bring the post-measurement state into the canonical logical-CNOT image. The specific function is derived from the surgery literature; placeholder here.
defapply_schedule
def apply_schedule (s : LogicalState_4_2_2_pair) :
    List PPM → List MeasurementOutcome × LogicalState_4_2_2_pair
  | [] => ([], s)
  | ppm :: rest =>
      let (out_head, s_after_head)
*Apply a sequence of PPMs to a LogicalState**, collecting outcomes left-to-right. Iterated `apply_PPM`.
defapply_surgery_with_corrections
def apply_surgery_with_corrections (s : LogicalState_4_2_2_pair)
    (schedule : List PPM)
    (_correction_fn : List MeasurementOutcome → PauliString) :
    LogicalState_4_2_2_pair
*Apply surgery with corrections**: applies the schedule, collects outcomes, computes the correction Pauli string, and applies it to the post-state. *Specification** (`TODO_apply_surgery_specification`): 1. The output state lies in the joint codespace (`in_codespace` preserved). 2. For input `s` representing a tensor-product logical state `|ψ_L⟩ ⊗ |φ_R⟩`, the output represents `CNOT_L1,R1 (|ψ_L⟩ ⊗ |φ_R⟩)`. 3. Outcome 1 above is the structural commitment; outcome 2 is the operational claim verified by Iter 148's `Code4Code4_surgery_implements_logical_CNOT`. For now: applies the schedule (collecting outcomes), then returns the post-state UNCORRECTED — the correction-function multiplication needs `PauliString.toMatrix` + matrix multiplication, deferred.
example(example)
example (s : LogicalState_4_2_2_pair) :
    (apply_schedule s Code4Code4_CNOT_surgery_schedule).1.length = 5
*Structural sanity for the 5-PPM schedule**: applying `Code4Code4_CNOT_surgery_schedule` collects exactly 5 outcomes. Decide-witness of the structural commitment.
example(example)
example (outs : List MeasurementOutcome) :
    Code4Code4_CNOT_correction_fn outs = PauliString.id 8
*Correction function placeholder structural check**: at any outcome list, the placeholder returns the 8-qubit identity string.
deflogical_CNOT_L1_R1
def logical_CNOT_L1_R1 (s : LogicalState_4_2_2_pair) : LogicalState_4_2_2_pair
*Abstract logical-CNOT image on the joint LogicalState**: placeholder for the function `|ψ⟩ ↦ CNOT_L1,R1 |ψ⟩` on LogicalStates. Returns the input unchanged for now (a placeholder identity). Real implementation requires the logical-CNOT matrix on the 16-dim codespace.
theoremCode4Code4_surgery_implements_logical_CNOT
theorem Code4Code4_surgery_implements_logical_CNOT
    (s : LogicalState_4_2_2_pair) :
    apply_surgery_with_corrections s
        Code4Code4_CNOT_surgery_schedule
        Code4Code4_CNOT_correction_fn
      = logical_CNOT_L1_R1 s
*THE PHASE B OPERATIONAL EMERGENT-ACTION THEOREM** (Iter 148): applying the 5-PPM CNOT surgery schedule with the standard correction function to a joint LogicalState yields the same state as applying the logical CNOT directly. *Status**: stated using Iter 145-147 infrastructure. Holds by `rfl` AT THE PLACEHOLDER LAYER — both `apply_surgery_with_corrections` and `logical_CNOT_L1_R1` are currently identities on `s`, so they trivially agree. The operational content emerges as the placeholders are tightened to their real matrix-level definitions via `PauliString.toMatrix` infrastructure. The theorem's *structural shape** is now committed; future work fills in the operational semantics underneath, after which this theorem will be a real (non-trivial) claim.

FormalRV.PPM.MagicGadgetInterface

FormalRV/PPM/MagicGadgetInterface.lean
FormalRV.PPM.MagicGadgetInterface — the ANCILLA-CARRYING gadget-realization predicate, discharged by the REAL T-gadget (not the `rfl` baseline). The operator-level `RealizesUpToFrame op frame U := op = frame * U` in `PPMCompilerCorrectness` cannot express a measurement-based gadget, because such a gadget consumes a magic ANCILLA and acts on the data only after measurement + correction. The right predicate is therefore on the magic-extended ACTION: `MagicRealizes G magic U` :⇔ ∀ ψ, G · (ψ ⊗ magic) = c • ((U · ψ) ⊗ anc) for some ancilla `anc`, scalar `c`. i.e. running the data state `ψ` together with the magic state `magic` through the gadget operator `G` teleports `U · ψ` onto the data register (the ancilla collapses, with a Born/frame scalar). The headline `tGadget_magic_realizes` discharges this for the T gate using the REAL teleportation `TGadgetTeleport.t_gadget_with_feedback` (ancilla `|T⟩`, CNOT, Z-measure, classically-controlled `S`). So the gate realization is the genuine gadget theorem — NOT `compile := uc_eval` closing by `rfl`. Kernel-clean.
defMagicRealizes
def MagicRealizes {dD dA : Nat}
    (G : Square (dD + dA)) (magic : StateVec dA) (U : Square dD) : Prop
*Ancilla-carrying realization.** The gadget operator `G` on the data⊗ancilla space realizes the gate `U` on the data register, consuming the magic state `magic`: for every data input `ψ`, `G · (ψ ⊗ magic)` is `(U · ψ) ⊗ anc` up to a scalar. This is the measurement-based analogue of `RealizesUpToFrame`, expressed on the magic-extended action.
deftMat
noncomputable def tMat : Matrix (Fin 2) (Fin 2) ℂ
The `T`-gate matrix `diag(1, ω)` (`ω = e^{iπ/4}`).
theoremtMat_apply
theorem tMat_apply (ψ : StateVec 1) : tMat * ψ = Tdata ψ
`tMat` acts as `Tdata`: `tMat · ψ = T|ψ⟩`.
theoremtGadget_magic_realizes
theorem tGadget_magic_realizes (b : Bool) :
    MagicRealizes (dD
*The real T-gadget DISCHARGES `MagicRealizes` for the T gate.** For each measurement outcome `b`, the gadget operator `S_feedback · Z-measure · CNOT` realizes the `T`-matrix on the data register using the magic state `|T⟩` — witnessed by `t_gadget_with_feedback`. This is a genuine (non-`rfl`) discharge: `realize` IS the proven teleportation, so the ancilla-carrying interface is fillable with REAL measurement-based content.
theoremmagic_realizes_chain
theorem magic_realizes_chain {dD dA1 dA2 : Nat}
    {G1 : Square (dD + dA1)} {m1 : StateVec dA1} {U1 : Square dD}
    {G2 : Square (dD + dA2)} {m2 : StateVec dA2} {U2 : Square dD}
    (h1 : MagicRealizes G1 m1 U1) (h2 : MagicRealizes G2 m2 U2) (ψ : StateVec dD) :
    ∃ (anc1 : StateVec dA1) (anc2 : StateVec dA2) (c1 c2 : ℂ),
      G1 * (ψ ⊗ᵥ m1) = c1 • ((U1 * ψ) ⊗ᵥ anc1)
      ∧ G2 * ((U1 * ψ) ⊗ᵥ m2) = c2 • (((U2 * U1) * ψ) ⊗ᵥ anc2)
*Realizations CHAIN on the data register.** If `G₁` realizes `U₁` (consuming magic `m₁`) and `G₂` realizes `U₂` (consuming magic `m₂`), then feeding the data output `U₁·ψ` of the first gadget into the second realizes the COMPOSITE gate `U₂·U₁` on the data register. This is the gate-by-gate composition of measurement-based gadgets at the effective-data level: each gadget consumes its own magic ancilla, and the data-register gate actions compose exactly — the property a full circuit's PPM compilation needs. (The data-register chaining; assembling the gadgets into a SINGLE operator on `data ⊗ anc₁ ⊗ anc₂` is the further tensor-embedding step.)

FormalRV.PPM.MagicStateTeleport

FormalRV/PPM/MagicStateTeleport.lean
FormalRV.PPM.MagicStateTeleport — the measurement-based gate teleportation protocol for the `T` gate, proved correct on state vectors (Ask 2, item 2). ## The protocol To apply `T` to a data qubit `|ψ⟩` using one `|T⟩ = (|0⟩+ω|1⟩)/√2` magic state (ω = e^{iπ/4}): 1. prepare `|ψ⟩ ⊗ |T⟩`; 2. apply `CNOT` (data controls the magic ancilla); 3. measure the ancilla in the `Z` basis; outcome 0 ⇒ the data qubit is `T|ψ⟩` (no correction); outcome 1 ⇒ apply the Clifford correction `S` ⇒ `T|ψ⟩`. This is the canonical *measurement-and-correct* gate teleportation: a non-Clifford gate is realised by consuming a magic state, a Clifford (CNOT) interaction, a measurement, and a Clifford (S) Pauli/phase correction. Both measurement branches are proved here for an arbitrary input `|ψ⟩`, sorry-free. ## Honesty boundary This is the **state-vector** correctness of the protocol (unnormalised post-measurement states; the `1/√2` / `ω/√2` factors are the Born amplitudes). Outcome probabilities and the renormalisation are the Born-rule layer (`prob_outcome`), not re-derived here. The analogous CCZ gate teleportation (Litinski's 6-PPM protocol) acts on a 6-qubit register (64×64); its Bell-measurement step is left cited. The `T` protocol here is the fully-proved measurement- teleportation instance.
deftKet
noncomputable def tKet : StateVec 1
The `T` magic state `|T⟩ = (|0⟩ + ω|1⟩)/√2`.
defTdata
noncomputable def Tdata (ψ : StateVec 1) : StateVec 1
`T|ψ⟩ = ψ₀|0⟩ + ω·ψ₁|1⟩` (the `T` gate is `diag(1, ω)`).
defprojLow0
def projLow0 : Matrix (Fin 4) (Fin 4) ℂ
`Z`-measurement projector for ancilla outcome 0 (keep low bit 0: indices 0,2).
defprojLow1
def projLow1 : Matrix (Fin 4) (Fin 4) ℂ
`Z`-measurement projector for ancilla outcome 1 (keep low bit 1: indices 1,3).
defShigh
noncomputable def Shigh : Matrix (Fin 4) (Fin 4) ℂ
The `S = diag(1, i)` correction on the data (high) qubit.
theorem_sq
theorem ω_sq : ω ^ 2 = Complex.I
`ω² = i`: the T phase squared is the S phase (`e^{iπ/2} = i`).
theoremt_teleport_outcome_0
theorem t_teleport_outcome_0 (ψ : StateVec 1) :
    projLow0 * (cnotMatrix * (ψ ⊗ᵥ tKet))
      = (1 / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 0 : StateVec 1))
*Measurement-teleportation, outcome 0.** After CNOT and projecting the ancilla onto `|0⟩`, the data qubit carries `T|ψ⟩` (up to the `1/√2` Born amplitude).
theoremt_teleport_outcome_1
theorem t_teleport_outcome_1 (ψ : StateVec 1) :
    Shigh * (projLow1 * (cnotMatrix * (ψ ⊗ᵥ tKet)))
      = (ω / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 1 : StateVec 1))
*Measurement-teleportation, outcome 1.** After CNOT, projecting the ancilla onto `|1⟩`, and applying the Clifford correction `S` on the data qubit, the data qubit again carries `T|ψ⟩` (up to the `ω/√2` Born amplitude).
theoremt_teleport_data_is_T
theorem t_teleport_data_is_T (ψ : StateVec 1) :
    (projLow0 * (cnotMatrix * (ψ ⊗ᵥ tKet))
        = (1 / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 0 : StateVec 1)))
    ∧ (Shigh * (projLow1 * (cnotMatrix * (ψ ⊗ᵥ tKet)))
        = (ω / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 1 : StateVec 1)))

FormalRV.PPM.ModMultPPMResource

FormalRV/PPM/ModMultPPMResource.lean
FormalRV.PPM.ModMultPPMResource — END-TO-END semantically-verified PPM resource bound for the modular multiplier (the substantive mod-exp building block). Welds two proofs about the SAME Gate IR term `sqir_modmult_const_gate bits N a`: SEMANTICS: `sqir_modmult_const_gate_target_decode` — it computes `(a · m) % N` into the accumulator register (no sorry, axiom-clean); RESOURCE: `tcount_sqir_modmult_const_gate_le` — its T-count is `≤ 56·bits²`, hence its Toffoli count is `≤ 8·bits²`, hence (through the verified `Gate → PPM` bridge) its PPM compilation uses `≤ 8·bits²` CCZ magic states. So the per-modmult factor of the un-windowed schoolbook count is no longer an abstract `def`: it is a proved upper bound on a circuit PROVED to multiply. Later sections make these EXACT (`= 56·bits²`/`112·bits²`) for valid Shor bases, bind the count to the actual verified oracle `sqir_modmult_MCP_gate` (§7), and count the whole arithmetic mod-exp on that oracle (§8 → `32·bits³` Toffolis, `274 877 906 944` at 2048). ## Honest note on the control overhead (why the arithmetic count is the clean one) The verified Shor algorithm's modular exponentiation is `controlled_powers m u`, which applies the GENERIC `control i` (UnitaryOps) to each oracle. `control` of a CNOT is a Toffoli, but `control` of a rotation is `controlled_R`, which emits `R(±θ/2)`. Since the oracle's Toffolis are decomposed to `7·T` (BaseUCom.CCX) before control, controlling a `T` (θ=π/4) yields `R(π/8)` — NOT a Clifford+T angle. So the FULL controlled mod-exp is not a Clifford+T circuit, and a magic-state count of it is ill-posed for this implementation without an extra rotation-synthesis layer. The clean, exact, Clifford+T resource is the ARITHMETIC (uncontrolled-oracle) count here; claiming a single magic-state number for the generic-control overhead would be unsound, so it is deliberately excluded and flagged. No `sorry`, no new `axiom`.
theoremtoffCount_sqir_modmult_const_gate_le
theorem toffCount_sqir_modmult_const_gate_le (bits N a : Nat) :
    toffCount (sqir_modmult_const_gate bits N a) ≤ 8 * bits ^ 2
Toffoli count of the verified modular multiplier `≤ 8·bits²` (from `tcount ≤ 56·bits²` and `tcount = 7·toffCount`).
theoremnumCCZMagic_sqir_modmult_const_gate_le
theorem numCCZMagic_sqir_modmult_const_gate_le (na bits N a : Nat) :
    numCCZMagic (circuitToPPM na (gateToHL (sqir_modmult_const_gate bits N a))) ≤ 8 * bits ^ 2
PPM CCZ-magic states to teleport-compile the verified modular multiplier `≤ 8·bits²`.
theoremverified_modmult_end_to_end
theorem verified_modmult_end_to_end
    (bits N a m : Nat) (hbits : 1 ≤ bits) (hN_pos : 0 < N)
    (hN : N ≤ 2 ^ bits) (hN2 : 2 * N ≤ 2 ^ bits) (hm : m < 2 ^ bits) :
    cuccaro_target_val bits 2
        (Gate.applyNat (sqir_modmult_const_gate bits N a) (sqir_mult_input_F bits m 0))
      = (a * m) % N
    ∧ numCCZMagic (circuitToPPM 0
          (gateToHL (sqir_modmult_const_gate bits N a))) ≤ 8 * bits ^ 2
*END-TO-END SEMANTICALLY-VERIFIED PPM RESOURCE BOUND (modular multiplier).** For the verified out-of-place modular multiplier (under the SQIR sizing hypotheses), ONE Gate IR term simultaneously (a) computes `(a · m) % N` into the accumulator, AND (b) costs `≤ 8·bits²` CCZ magic states when compiled to PPM. Both conjuncts are about the SAME `sqir_modmult_const_gate bits N a`.
theoremshor2048_per_modmult_CCZMagic_le
theorem shor2048_per_modmult_CCZMagic_le (na N a : Nat) :
    numCCZMagic (circuitToPPM na (gateToHL (sqir_modmult_const_gate 2048 N a))) ≤ 33554432
At the RSA-2048 modulus width `bits = 2048`, the verified modular multiplier uses `≤ 8·2048² = 33 554 432` CCZ magic states. Multiplying by the `2n = 4096` exponent register (structural, not welded) reproduces the whole-algorithm `137 438 953 472`.
example(example)
example : 4096 * 33554432 = 137438953472
theoremtoffCount_shorModExp
theorem toffCount_shorModExp (bits N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    toffCount (shorModExp bits N a) = 16 * bits ^ 3
EXACT Toffoli count of the concrete Shor mod-exp: `16·bits³` (from `tcount = 112·bits³` and `tcount = 7·toffCount`).
theoremnumCCZMagic_shorModExp
theorem numCCZMagic_shorModExp (na bits N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    numCCZMagic (circuitToPPM na (gateToHL (shorModExp bits N a))) = 16 * bits ^ 3
EXACT CCZ-magic count of the PPM-compiled concrete Shor mod-exp: `16·bits³`.
theoremnumMeas_shorModExp
theorem numMeas_shorModExp (na bits N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    numMeas (circuitToPPM na (gateToHL (shorModExp bits N a))) = 48 * bits ^ 3
EXACT Z-basis Pauli-measurement count of the PPM-compiled concrete Shor mod-exp: `48·bits³`.
theoremshor2048_CCZMagic_outOfPlaceModel
theorem shor2048_CCZMagic_outOfPlaceModel (na N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    numCCZMagic (circuitToPPM na (gateToHL (shorModExp 2048 N a))) = 137438953472
EXACT CCZ-magic count of the OUT-OF-PLACE COUNTING MODEL `shorModExp 2048 N a`: `137 438 953 472` (and `412 316 860 416` measurements). ⚠ HONEST LABEL (counting audit 2026-06-03): the count is exact for this concrete term, but the term is a chain of OUT-OF-PLACE `const_gate`s — NOT the verified Shor oracle and NOT a valid modular-exponentiation circuit (no feedback). The verified-oracle arithmetic figure is `shor2048_CCZMagic_verified = 274 877 906 944 = 2×` this (§8) — that is the honest headline; this `137 438 953 472` UNDERSTATES the verified-oracle cost by exactly the in-place forward+uncompute factor of 2. Do not cite this as "the verified circuit".
theoremshor2048_Meas_outOfPlaceModel
theorem shor2048_Meas_outOfPlaceModel (na N a : Nat)
    (hcop : Nat.Coprime a N) (hodd : Odd N) (h1 : 1 < N) :
    numMeas (circuitToPPM na (gateToHL (shorModExp 2048 N a))) = 412316860416
theoremtoffCount_sqir_modmult_MCP_gate
theorem toffCount_sqir_modmult_MCP_gate (bits N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    toffCount (sqir_modmult_MCP_gate bits N a ainv) = 16 * bits ^ 2
theoremverified_MCP_oracle_end_to_end
theorem verified_MCP_oracle_end_to_end
    (bits N a ainv : Nat)
    (hbits : 1 ≤ bits) (hN_pos : 0 < N) (hN : N ≤ 2 ^ bits) (hN2 : 2 * N ≤ 2 ^ bits)
    (hodd : Odd N) (h1 : 1 < N) (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (h_inv : a * ainv % N = 1) :
    FormalRV.SQIRPort.MultiplyCircuitProperty a N bits (sqir_modmult_rev_anc bits)
        (Gate.toUCom (sqir_total_dim bits) (sqir_modmult_MCP_gate bits N a ainv))
    ∧ numCCZMagic (circuitToPPM 0 (gateToHL (sqir_modmult_MCP_gate bits N a ainv)))
        = 16 * bits ^ 2
*END-TO-END on the ACTUAL verified Shor oracle.** ONE term `sqir_modmult_MCP_gate bits N a ainv` simultaneously (a) computes `|x⟩ ↦ |a·x mod N⟩` (its `Gate.toUCom` satisfies `MultiplyCircuitProperty` — the property the verified Shor algorithm relies on) and (b) costs EXACTLY `16·bits²` CCZ magic states in PPM.
theoremtoffCount_shorModExpVerified
theorem toffCount_shorModExpVerified (bits N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    toffCount (shorModExpVerified bits N a ainv) = 32 * bits ^ 3
theoremnumCCZMagic_shorModExpVerified
theorem numCCZMagic_shorModExpVerified (na bits N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    numCCZMagic (circuitToPPM na (gateToHL (shorModExpVerified bits N a ainv))) = 32 * bits ^ 3
theoremshor2048_CCZMagic_verified
theorem shor2048_CCZMagic_verified (na N a ainv : Nat)
    (hcop : Nat.Coprime a N) (hcopinv : Nat.Coprime ainv N)
    (hpos : 0 < ainv) (hlt : ainv < N) (hodd : Odd N) (h1 : 1 < N) :
    numCCZMagic (circuitToPPM na (gateToHL (shorModExpVerified 2048 N a ainv))) = 274877906944
*THE HONEST RSA-2048 ARITHMETIC HEADLINE — verified-oracle chain**: `32·2048³ = 274 877 906 944` CCZ magic states (count-only/scaffolded + arithmetic-only; see §8 note). This, not the 2× smaller out-of-place `137 438 953 472`, is the verified-oracle figure.

FormalRV.PPM.PPM

FormalRV/PPM/PPM.lean
FormalRV.BQCode.PPM — Pauli operators and Parallel Pauli-product Measurement scaffolding. Per CLAUDE.md scope expansion (2026-05-12) bringing the QEC stack in-scope, plus the Phase B roadmap (Iter 30 reflection): start formalizing the stabilizer measurement primitives that the qianxu cost claims load-bearingly assume. This file is the first piece of Phase B. It establishes the basic Pauli algebra primitives. Future ticks add: - Pauli strings (Iter 34) - PPM data type and basic semantics (Iter 35+) - Stabilizer simulator semantics - The Gidney measurement-based logical-AND as a concrete PPM sequence (closes Iter 25's 14n-vs-7n structural finding) - LP qLDPC parity-check matrix definition for a small instance Decoder correctness/runtime remains `axiom`. Atom-trapping physics remains `axiom`. PPM algebraic primitives + lattice surgery on small concrete codes are IN scope.
inductivePauli
inductive Pauli
Single-qubit Pauli operator. Matches the standard generators of the Pauli group P_1.
inductivePhase
inductive Phase
Phase factor that can multiply a Pauli operator. Group elements of `{+1, -1, +i, -i}`, encoded as four cases.
defPhase.mul
def Phase.mul : Phase → Phase → Phase
  | .pos, p => p
  | p, .pos => p
  | .neg, .neg => .pos
  | .neg, .posI => .negI
  | .neg, .negI => .posI
  | .posI, .neg => .negI
  | .posI, .posI => .neg
  | .posI, .negI => .pos
  | .negI, .neg => .posI
  | .negI, .posI => .pos
  | .negI, .negI => .neg
Phase multiplication: `Phase` is a group under multiplication, isomorphic to `Z/4Z`.
defmul
def mul : Pauli → Pauli → Phase × Pauli
  | .I, p => (.pos, p)
  | p, .I => (.pos, p)
  | .X, .X => (.pos, .I)
  | .Y, .Y => (.pos, .I)
  | .Z, .Z => (.pos, .I)
  | .X, .Y => (.posI, .Z)
  | .Y, .X => (.negI, .Z)
  | .Y, .Z => (.posI, .X)
  | .Z, .Y => (.negI, .X)
  | .Z, .X => (.posI, .Y)
  | .X, .Z => (.negI, .Y)
Pauli multiplication: emits the resulting Pauli plus a phase factor. Identities: `P · P = I` for all P; `X · Y = +iZ`; `Y · Z = +iX`; `Z · X = +iY`; and the swaps are `-i` instead of `+i`.
example(example)
example : mul .X .X = (.pos, .I)
example(example)
example : mul .X .Y = (.posI, .Z)
example(example)
example : mul .Y .X = (.negI, .Z)
example(example)
example : mul .Z .X = (.posI, .Y)
example(example)
example : (mul .X .Y).2 = (mul .Y .X).2
Anti-commutation: `X · Y` and `Y · X` differ only in phase.
example(example)
example : (mul .X .Y).1 = .posI ∧ (mul .Y .X).1 = .negI
And the phase differs by complex conjugation (here: `posI` vs `negI`).
defcommutes
def commutes (p q : Pauli) : Bool
`commutes p q` ↔ `p · q = q · p` as `Phase × Pauli`.
defanticommutes
def anticommutes (p q : Pauli) : Bool
`anticommutes p q` ↔ `p · q` and `q · p` have the same Pauli but opposite-sign phase factors (i.e., differ by an overall `-1`).
theoremcommutes_self
theorem commutes_self (p : Pauli) : commutes p p = true
Every Pauli commutes with itself.
theoremcommutes_I_left
theorem commutes_I_left (p : Pauli) : commutes .I p = true
Every Pauli commutes with the identity.
theoremcommutes_I_right
theorem commutes_I_right (p : Pauli) : commutes p .I = true
Every Pauli commutes with the identity (right).
example(example)
example : anticommutes .X .Y = true
X and Y anti-commute.
example(example)
example : anticommutes .Y .Z = true
Y and Z anti-commute.
example(example)
example : anticommutes .X .Z = true
X and Z anti-commute.
example(example)
example : commutes .X .Y = false
X and Y do NOT commute.
theoremdistinct_nonI_anticommute
theorem distinct_nonI_anticommute :
    ∀ p q : Pauli, p ≠ q → p ≠ .I → q ≠ .I → anticommutes p q = true
The single-qubit Pauli dichotomy: any two distinct non-identity Paulis anti-commute. **Foundational fact for stabilizer formalism**.
abbrevPauliString
abbrev PauliString
A Pauli string is a list of single-qubit Paulis. Index `i` corresponds to qubit `i`.
defPauliString.id
def PauliString.id (n : Nat) : PauliString
The identity n-qubit Pauli string: `[I, I, ..., I]`.
defPauliString.singleX
def PauliString.singleX (n i : Nat) : PauliString
The single-qubit-X string at qubit `i` in an `n`-qubit register: `[I, ..., I, X, I, ..., I]` with `X` at position `i`.
example(example)
example : PauliString.id 3 = [.I, .I, .I]
Smoke: identity string at n=3 is `[I, I, I]`.
example(example)
example : PauliString.singleX 3 1 = [.I, .X, .I]
Smoke: X at position 1 in a 3-qubit string is `[I, X, I]`.
inductivePPM_outcome
inductive PPM_outcome
Measurement outcome of a PPM: `0` if the eigenvalue is `+1`, `1` if the eigenvalue is `-1`. Matches the standard `Z`-basis convention.
example(example)
example : (PPM_outcome.zero = PPM_outcome.one) = False
Smoke: outcome equality is decidable.
structurePPM
structure PPM
A PPM primitive: input is the Pauli string to measure; output is the outcome. **Semantics defer** to a future tick — this is structural data only, sufficient to schedule and count PPM operations for the τ_s review. Carrying just the input string lets us cost-account PPMs without committing to a Hilbert-space semantics yet.
defPauliString.mul
def PauliString.mul : PauliString → PauliString → Pauli.Phase × PauliString
  | [], _ => (.pos, [])
  | _, [] => (.pos, [])
  | p :: ps, q :: qs =>
      let (φ_head, r_head)
Point-wise Pauli string multiplication with phase accumulation. Outputs `(overall_phase, result_string)`. The two input strings must have the same length (if not, the result is truncated to the shorter length — list-zip behavior).
example(example)
example : PauliString.mul [.I, .I] [.I, .I] = (.pos, [.I, .I])
`[I, I] · [I, I] = (+1, [I, I])`.
example(example)
example : PauliString.mul [.X, .Y] [.Y, .X] = (.pos, [.Z, .Z])
`[X, Y] · [Y, X] = (+i · -i, [Z, Z]) = (+1, [Z, Z])`.
example(example)
example : PauliString.mul [.X, .X, .X] [.X, .X, .X] = (.pos, [.I, .I, .I])
`[X, X, X] · [X, X, X] = (+1, [I, I, I])`. Pauli string squared is identity (each qubit's `X · X = +1·I`, phase product = +1).
example(example)
example : PauliString.mul [.X, .Z] [.Z, .X] = (.pos, [.Y, .Y])
`[X, Z] · [Z, X] = (-i · -i, [Y, Y]) = (-1, [Y, Y])`. Phase: X·Z = -iY, Z·X = +iY, product of phases = -i · +i = +1. Wait re-check: `Pauli.mul X Z = (negI, Y)` and `Pauli.mul Z X = (posI, Y)`, so the product of phases is `negI · posI = pos`. Verify via decide.
defPauliString.commutes
def PauliString.commutes (A B : PauliString) : Bool
Two Pauli strings commute iff `mul A B` and `mul B A` yield the same phase. (The resulting Pauli is identical by elementwise Pauli-mul determinism.)
example(example)
example : PauliString.commutes [.I, .I] [.I, .I] = true
`[I,I] commutes with [I,I]` trivially.
example(example)
example : PauliString.commutes [.X, .X] [.Z, .Z] = true
`[X,X]` commutes with `[Z,Z]`: 2 anti-commuting positions (even).
example(example)
example : PauliString.commutes [.X, .X, .X] [.Z, .Z, .Z] = false
`[X,X,X]` anti-commutes with `[Z,Z,Z]`: 3 anti-commuting positions (odd).
example(example)
example : PauliString.commutes [.X, .Y] [.Y, .X] = true
`[X,Y]` commutes with `[Y,X]`: both positions anti-commute, total 2 (even).
example(example)
example : PauliString.commutes [.X, .I] [.Z, .I] = false
`[X,I]` anti-commutes with `[Z,I]`: 1 anti-commuting position (odd).
example(example)
example : PauliString.commutes [.X, .X, .X, .X] [.Z, .Z, .Z, .Z] = true
*The 4-qubit code stabilizers commute**: `XXXX` and `ZZZZ` have 4 anti-commuting positions (even). This is the foundational fact for the 4-qubit error-detection code (target of Iter 39).
defCode4_S1
def Code4_S1 : PauliString
The X-stabilizer of the [[4,2,2]] code.
defCode4_S2
def Code4_S2 : PauliString
The Z-stabilizer of the [[4,2,2]] code.
defCode4_stabilizers
def Code4_stabilizers : List PauliString
The complete stabilizer generator list: `{S1, S2}`.
example(example)
example : Code4_S1.length = 4 ∧ Code4_S2.length = 4
Both stabilizers have length 4 (= n).
example(example)
example : PauliString.commutes Code4_S1 Code4_S1 = true
S1 commutes with itself (trivially).
example(example)
example : PauliString.commutes Code4_S2 Code4_S2 = true
S2 commutes with itself (trivially).
theoremCode4_stabilizers_commute
theorem Code4_stabilizers_commute :
    PauliString.commutes Code4_S1 Code4_S2 = true
*S1 and S2 commute** — the key code-validity condition. With 4 anti-commuting positions (X⊣Z at every qubit), the count is even, so they commute. This certifies that the stabilizer group is abelian and the code is well-defined.
theoremCode4_stabilizers_commute_symm
theorem Code4_stabilizers_commute_symm :
    PauliString.commutes Code4_S2 Code4_S1 = true
Mirror direction: S2 and S1 commute (commutation is symmetric).
defCode4_S3
def Code4_S3 : PauliString
*Third stabilizer-group element**: `S3 := S1 · S2 = YYYY` (with `.pos` phase). The full group is `{I, S1, S2, S3}` — the abelian subgroup of weight-4 even-parity Paulis.
example(example)
example :
    PauliString.mul Code4_S1 Code4_S2 = (Pauli.Phase.pos, Code4_S3)
*Decide-witness**: the product `S1 · S2` evaluates to `(.pos, S3)`. Verifies the third-element identity directly via Pauli multiplication, complementing the parity-based commutation theorems (Iter 99).
example(example)
example : PauliString.commutes Code4_S3 Code4_S3 = true
*Self-commutation of the third element**: `S3` commutes with itself (every PauliString does, trivially). Included for completeness of the stabilizer-group commutation table.
example(example)
example :
    PauliString.commutes Code4_S3 Code4_S1 = true
    ∧ PauliString.commutes Code4_S3 Code4_S2 = true
*`S3` commutes with both explicit generators**: since `S3 = S1 · S2` is a product of commuting stabilizers, it commutes with every element of the stabilizer group. Confirms `{S1, S2, S3}` is an abelian subset.
defPauli.toSymplectic
def Pauli.toSymplectic : Pauli → Bool × Bool
  | .I => (false, false)
  | .X => (true,  false)
  | .Y => (true,  true)
  | .Z => (false, true)
Symplectic representation of a single Pauli: `(x_bit, z_bit)`.
defPauliString.toSymplectic
def PauliString.toSymplectic (P : PauliString) : List Bool
Symplectic representation of a Pauli string: a single `List Bool` of length `2n`, structured as `[x_0, ..., x_{n-1}, z_0, ..., z_{n-1}]`.
defparity_check_matrix
def parity_check_matrix (stabilizers : List PauliString) : List (List Bool)
The **parity-check matrix** of a stabilizer code is the list of symplectic representations of its generators. As a `List (List Bool)`, it's a `k × 2n` matrix (k stabilizers, 2n columns).
example(example)
example :
    PauliString.toSymplectic Code4_S1
      = [true, true, true, true, false, false, false, false]
XXXX maps to [1,1,1,1 | 0,0,0,0].
example(example)
example :
    PauliString.toSymplectic Code4_S2
      = [false, false, false, false, true, true, true, true]
ZZZZ maps to [0,0,0,0 | 1,1,1,1].
example(example)
example :
    parity_check_matrix Code4_stabilizers
      = [[true, true, true, true, false, false, false, false],
         [false, false, false, false, true, true, true, true]]
Full [[4,2,2]] parity-check matrix has block-diagonal structure `[[1111|0000], [0000|1111]]` — the canonical CSS form for codes with X-only and Z-only stabilizers.
example(example)
example :
    ∀ row ∈ parity_check_matrix Code4_stabilizers, row.length = 8
Each row of the parity-check matrix has length 2n = 8 (for n=4).
defCode4Code4_merge_CNOT_PPM
def Code4Code4_merge_CNOT_PPM : PPM
The "merge" PPM for a CNOT (control patch L = qubits 0-3, target patch R = qubits 4-7): measure `XL ⊗ ZR`, i.e., XXXX on the first four qubits, ZZZZ on the next four.
defCode4Code4_split_L_X_PPM
def Code4Code4_split_L_X_PPM : PPM
"Split-L" PPM: measure left patch's `XXXX` stabilizer to detach.
defCode4Code4_split_R_Z_PPM
def Code4Code4_split_R_Z_PPM : PPM
"Split-R" PPM: measure right patch's `ZZZZ` stabilizer to detach.
defCode4Code4_check_L_Z_PPM
def Code4Code4_check_L_Z_PPM : PPM
"Check-L" PPM: stabilizer-round measurement on left patch (`ZZZZ` after the merge).
defCode4Code4_check_R_X_PPM
def Code4Code4_check_R_X_PPM : PPM
"Check-R" PPM: stabilizer-round measurement on right patch (`XXXX` after the merge).
defCode4Code4_CNOT_surgery_schedule
def Code4Code4_CNOT_surgery_schedule : List PPM
*Logical CNOT via lattice surgery** on two [[4,2,2]] patches. The total schedule is 5 PPMs (1 merge + 2 boundary checks + 2 splits). Each PPM corresponds to **one stabilizer cycle τ_s** in qianxu's timing model — so logical CNOT via surgery costs **5 τ_s** at this code's scale.
theoremCode4Code4_CNOT_surgery_count
theorem Code4Code4_CNOT_surgery_count :
    Code4Code4_CNOT_surgery_schedule.length = 5
The surgery schedule has 5 PPMs.
theoremPauliString.commutes_self
theorem PauliString.commutes_self (P : PauliString) :
    PauliString.commutes P P = true
*Every PauliString commutes with itself**. Direct consequence of `PauliString.commutes`'s reflexivity: phase of `mul P P` equals itself trivially. The Bool-valued equality reduces to `true` via `decide_eq_true rfl`.
theoremPauliString.commutes_symm
theorem PauliString.commutes_symm (A B : PauliString) :
    PauliString.commutes A B = PauliString.commutes B A
*PauliString commutation is symmetric**: `commutes A B = commutes B A`. The Bool-valued equality `(phase A B).1 = (phase B A).1` is symmetric by `eq_comm`. Useful for stabilizer-group proofs where we can pick either ordering.
theoremPauliString.mul_id_left_phase_pos
theorem PauliString.mul_id_left_phase_pos (n : Nat) (P : PauliString) :
    (PauliString.mul (PauliString.id n) P).1 = Pauli.Phase.pos
*Auxiliary lemma**: the phase of `mul (id n) P` is always `.pos`. The identity Pauli `.I` commutes with everything at the single-qubit level, so each pairwise multiplication contributes a `.pos` phase, and the product of `.pos`s is `.pos`. Proven by simultaneous induction on `n` and the list structure of `P`.
theoremPauliString.commutes_I_left
theorem PauliString.commutes_I_left (n : Nat) (P : PauliString) :
    PauliString.commutes (PauliString.id n) P = true
*`PauliString.commutes_I_left` (parametric)**: the identity PauliString of any length commutes with any other PauliString. Direct corollary: both `(mul (id n) P).1` and `(mul P (id n)).1` equal `.pos` (the latter via symmetry of Pauli mul-with-I), so they're equal, so commutes returns true. Lifts the single-qubit `commutes_I_left` (Iter 33) to multi-qubit. Closes the parametric form that Iter 98's decide-examples only covered at n=4.
theoremPauliString.commutes_I_right
theorem PauliString.commutes_I_right (n : Nat) (P : PauliString) :
    PauliString.commutes P (PauliString.id n) = true
*`PauliString.commutes_I_right` (parametric)** — symmetric counterpart of `commutes_I_left`.
theoremPauliString.id_commutes_with_all
theorem PauliString.id_commutes_with_all (n : Nat) (stabs : List PauliString) :
    ∀ S ∈ stabs, PauliString.commutes (PauliString.id n) S = true
*Corollary**: for ANY list of stabilizers (or PauliStrings in general), the identity PauliString commutes with all of them. Useful for verifying that the identity is a member of any stabilizer group: the trivial stabilizer `I⊗I⊗...⊗I` always commutes with all generators.
theoremPauliString.mul_id_left_eq
theorem PauliString.mul_id_left_eq : ∀ (P : PauliString),
    PauliString.mul (PauliString.id P.length) P = (Pauli.Phase.pos, P)
  | [] => rfl
  | q :: ps =>
*Left identity for PauliString.mul (length-matched case)**: `mul (id P.length) P = (.pos, P)` — the identity string of the same length multiplied with `P` returns `P` with phase `.pos`. Parametric proof by induction on `P`, using `Pauli.mul .I p = (.pos, p)` (first clause of `Pauli.mul`) + IH for the tail.
theoremPauliString.mul_id_right_eq
theorem PauliString.mul_id_right_eq : ∀ (P : PauliString),
    PauliString.mul P (PauliString.id P.length) = (Pauli.Phase.pos, P)
  | [] => rfl
  | q :: ps =>
*Right identity for PauliString.mul (length-matched case)**: `mul P (id P.length) = (.pos, P)`. Symmetric counterpart of `mul_id_left_eq`. Requires `cases q` since `Pauli.mul q .I`'s second clause requires `q` to be a concrete constructor (the first clause `.I, p => ...` is tried first).
theoremPauliString.length_id
theorem PauliString.length_id (n : Nat) :
    (PauliString.id n).length = n
`(PauliString.id n).length = n`. Basic length property useful for stabilizer-group length-matching arguments.
theoremPauliString.length_singleX
theorem PauliString.length_singleX (n i : Nat) :
    (PauliString.singleX n i).length = n
`(PauliString.singleX n i).length = n`. Companion to `length_id`: the single-X string at position `i` preserves the register width because `List.set` doesn't change the underlying list length. Useful for matching against stabilizer-group length requirements when single-qubit X strings appear as generators.
theoremPauliString.length_mul
theorem PauliString.length_mul (P Q : PauliString) :
    (PauliString.mul P Q).2.length = min P.length Q.length
*Length under `PauliString.mul`**: the length of the product string is the minimum of the two operand lengths. Direct consequence of `mul`'s list-zip recursion: each cons step consumes one element of each side and produces one element, and either empty input yields an empty result. Useful for establishing length-matching invariants in stabilizer-group composition (where stabilizers of equal length must produce a result of that same length, i.e., `min n n = n`).
theoremPauliString.length_mul_of_eq_length
theorem PauliString.length_mul_of_eq_length (P Q : PauliString)
    (h : P.length = Q.length) :
    (PauliString.mul P Q).2.length = P.length
*Equal-length corollary of `length_mul`**: when both operands have the same length, the product string has that same length. The expected shape for stabilizer-group composition where all generators have the fixed register width `n`. Direct from `length_mul` + `Nat.min_self`.
theoremPauliString.length_mul_singleX
theorem PauliString.length_mul_singleX (n i : Nat) (P : PauliString)
    (h : P.length = n) :
    (PauliString.mul P (PauliString.singleX n i)).2.length = n
*Length under `mul` with `singleX`**: when an n-length PauliString is multiplied with the n-length single-X string, the result has length n. Direct composition of `length_mul_of_eq_length` (this file) + `length_singleX` (line ~680). Useful for stabilizer- composition lemmas where a general string is multiplied against a single-X generator.
theoremPauliString.toSymplectic_length
theorem PauliString.toSymplectic_length (P : PauliString) :
    P.toSymplectic.length = 2 * P.length
*Symplectic length**: the symplectic representation of an n-qubit PauliString has length `2 · n`. The encoding splits each Pauli into its (x_i, z_i) bits and concatenates the X-half `[x_0, ..., x_{n-1}]` with the Z-half `[z_0, ..., z_{n-1}]`.
theoremPauliString.toSymplectic_id
theorem PauliString.toSymplectic_id (n : Nat) :
    (PauliString.id n).toSymplectic = List.replicate (2 * n) false
*Symplectic representation of the identity string**: maps to a list of `2*n` `false` bits (no X bits, no Z bits). Direct unfold + `List.map_replicate` (each Pauli.I has `(false, false)` per `Pauli.toSymplectic`) + `List.append_replicate`.
theoremparity_check_matrix_length
theorem parity_check_matrix_length (stabs : List PauliString) :
    (parity_check_matrix stabs).length = stabs.length
*Parity-check matrix row count**: the parity-check matrix has one row per stabilizer generator. Direct from the def `parity_check_matrix = stabs.map PauliString.toSymplectic`.
example(example)
example :
    ∀ ppm ∈ Code4Code4_CNOT_surgery_schedule, ppm.measure.length = 8
Each PPM in the schedule operates on 8 physical qubits (the combined patch area).
example(example)
example : PauliString.commutes (PauliString.id 4) Code4_S1 = true
`[I, I, I, I]` commutes with the X-stabilizer `[X, X, X, X]`.
example(example)
example : PauliString.commutes (PauliString.id 4) Code4_S2 = true
`[I, I, I, I]` commutes with the Z-stabilizer `[Z, Z, Z, Z]`.
example(example)
example : PauliString.commutes (PauliString.id 4) (PauliString.id 4) = true
`[I, I, I, I]` commutes with itself.
example(example)
example : PauliString.commutes (PauliString.id 4) [.Y, .Y, .Y, .Y] = true
`[I, I, I, I]` commutes with `[Y, Y, Y, Y]`.
example(example)
example :
    PauliString.commutes (PauliString.id 4) (PauliString.singleX 4 0) = true
    ∧ PauliString.commutes (PauliString.id 4) (PauliString.singleX 4 1) = true
    ∧ PauliString.commutes (PauliString.id 4) (PauliString.singleX 4 2) = true
    ∧ PauliString.commutes (PauliString.id 4) (PauliString.singleX 4 3) = true
`[I, I, I, I]` commutes with the single-qubit-X strings at each position.
defPPM.commutes_with
def PPM.commutes_with (ppm : PPM) (S : PauliString) : Bool
A PPM commutes with a PauliString iff their measure strings commute (in the Pauli group sense — phases match). Thin wrapper around `PauliString.commutes`.
defCode4Code4_XXXX_L
def Code4Code4_XXXX_L : PauliString
Extended X stabilizer on the left [[4,2,2]] patch (qubits 0-3), identity on the right (qubits 4-7).
defCode4Code4_ZZZZ_L
def Code4Code4_ZZZZ_L : PauliString
Extended Z stabilizer on the left [[4,2,2]] patch.
defCode4Code4_XXXX_R
def Code4Code4_XXXX_R : PauliString
Extended X stabilizer on the right [[4,2,2]] patch.
defCode4Code4_ZZZZ_R
def Code4Code4_ZZZZ_R : PauliString
Extended Z stabilizer on the right [[4,2,2]] patch.
defCode4Code4_stabilizers
def Code4Code4_stabilizers : List PauliString
The four extended stabilizers of the 2-patch [[4,2,2]] system.
example(example)
example :
    Code4Code4_merge_CNOT_PPM.commutes_with Code4Code4_XXXX_L = true
    ∧ Code4Code4_merge_CNOT_PPM.commutes_with Code4Code4_ZZZZ_L = true
    ∧ Code4Code4_merge_CNOT_PPM.commutes_with Code4Code4_XXXX_R = true
    ∧ Code4Code4_merge_CNOT_PPM.commutes_with Code4Code4_ZZZZ_R = true
*Surgery review**: the merge CNOT PPM (measure `XL ⊗ ZR`) commutes with all four extended stabilizers — the structural correctness condition for surgery to be a valid stabilizer measurement. Each pair anti-commutes at 4 positions (even parity → overall commute). All 4 decide-checked.
example(example)
example :
    Code4Code4_split_L_X_PPM.commutes_with Code4Code4_XXXX_L = true
    ∧ Code4Code4_split_L_X_PPM.commutes_with Code4Code4_ZZZZ_L = true  -- 4 anti-comm = even = comm
    ∧ Code4Code4_split_L_X_PPM.commutes_with Code4Code4_XXXX_R = true
    ∧ Code4Code4_split_L_X_PPM.commutes_with Code4Code4_ZZZZ_R = true
The split-L PPM (measure `XXXX_L`) commutes with `XXXX_L` (self), `XXXX_R` (disjoint qubits → all I products), and `ZZZZ_R` (disjoint). It **anti-commutes** with `ZZZZ_L` (4 anti-commuting positions on the left).
example(example)
example :
    ∀ ppm ∈ Code4Code4_CNOT_surgery_schedule,
    ∀ S ∈ Code4Code4_stabilizers, ppm.commutes_with S = true
All 5 PPMs in the CNOT surgery schedule commute with all 4 extended stabilizers — verifying the surgery preserves the stabilizer code structure. **20 commutation checks**, all `decide`-true.
defCode4_X_L1
def Code4_X_L1 : PauliString
Logical X on logical qubit 1 of [[4,2,2]]: `XXII`.
defCode4_X_L2
def Code4_X_L2 : PauliString
Logical X on logical qubit 2 of [[4,2,2]]: `XIXI`.
defCode4_Z_L1
def Code4_Z_L1 : PauliString
Logical Z on logical qubit 1 of [[4,2,2]]: `ZIZI`.
defCode4_Z_L2
def Code4_Z_L2 : PauliString
Logical Z on logical qubit 2 of [[4,2,2]]: `ZZII`.
example(example)
example :
    PauliString.commutes Code4_X_L1 Code4_S1 = true
    ∧ PauliString.commutes Code4_X_L1 Code4_S2 = true
    ∧ PauliString.commutes Code4_X_L2 Code4_S1 = true
    ∧ PauliString.commutes Code4_X_L2 Code4_S2 = true
    ∧ PauliString.commutes Code4_Z_L1 Code4_S1 = true
    ∧ PauliString.commutes Code4_Z_L1 Code4_S2 = true
    ∧ PauliString.commutes Code4_Z_L2 Code4_S1 = true
    ∧ PauliString.commutes Code4_Z_L2 Code4_S2 = true
*Logical operators commute with both stabilizers**. Standard requirement for valid logical operators of a stabilizer code: they preserve the code subspace. 8 decide checks (4 logicals × 2 stabilizers).
example(example)
example :
    PauliString.commutes Code4_X_L1 Code4_Z_L1 = false
    ∧ PauliString.commutes Code4_X_L2 Code4_Z_L2 = false
*Logical-pair anti-commutation**: `X_L1` and `Z_L1` anti-commute (1 anti-commuting position = odd → anti-commute overall). Same for `X_L2` and `Z_L2`.
example(example)
example :
    PauliString.commutes Code4_X_L1 Code4_Z_L2 = true
    ∧ PauliString.commutes Code4_X_L2 Code4_Z_L1 = true
    ∧ PauliString.commutes Code4_X_L1 Code4_X_L2 = true
    ∧ PauliString.commutes Code4_Z_L1 Code4_Z_L2 = true
*Independent logical qubits commute**: `X_L1 / Z_L2`, `X_L2 / Z_L1`, `X_L1 / X_L2`, `Z_L1 / Z_L2` all commute.
defCode4Code4_X_L1_left
def Code4Code4_X_L1_left : PauliString
Extended `X_L1` for the left patch in the 2-patch system.
defCode4Code4_X_L2_left
def Code4Code4_X_L2_left : PauliString
Extended `X_L2` for the left patch.
defCode4Code4_Z_L1_left
def Code4Code4_Z_L1_left : PauliString
Extended `Z_L1` for the left patch.
defCode4Code4_Z_L2_left
def Code4Code4_Z_L2_left : PauliString
Extended `Z_L2` for the left patch.
defCode4Code4_X_L1_right
def Code4Code4_X_L1_right : PauliString
Extended `X_L1` for the right patch.
defCode4Code4_X_L2_right
def Code4Code4_X_L2_right : PauliString
Extended `X_L2` for the right patch.
defCode4Code4_Z_L1_right
def Code4Code4_Z_L1_right : PauliString
Extended `Z_L1` for the right patch.
defCode4Code4_Z_L2_right
def Code4Code4_Z_L2_right : PauliString
Extended `Z_L2` for the right patch.
defCode4Code4_logicals
def Code4Code4_logicals : List PauliString
The eight extended logicals collected as a list.
example(example)
example :
    ∀ ppm ∈ Code4Code4_CNOT_surgery_schedule,
    ∀ L ∈ Code4Code4_logicals, ppm.commutes_with L = true
*40-check theorem**: every surgery PPM commutes with every extended logical operator. *⚠ REVIEW FINDING (Iter 297, 2026-05-14, via Qiskit verification per John's directive)**: this 40-way commutation is also the SMOKING GUN that `Code4Code4_CNOT_surgery_schedule` does NOT implement a logical CNOT. If every PPM commutes with every logical, the projection-onto-+1-eigenspace of each PPM leaves each logical operator untouched on the codespace, so the joint schedule's logical-conjugation action is the IDENTITY, not CNOT. The original docstring above claimed that "the actual logical CNOT action emerges from the SCHEDULE (merge + checks + splits combine to copy logical X from control to target, and logical Z from target to control)." This claim is FALSE — Pauli-feedback corrections after a measurement chain can only multiply by a Pauli operator, and Pauli operators that preserve the codespace are stabilizers (which act as identity on logical states). No classical-controlled correction can transform identity-action into CNOT-action. Verified out-of-band by: `PyCircuits/qec/code422_cnot_surgery_qiskit.py` — runs the all- plus-outcome branch of the schedule and compares to transversal CNOT (the genuinely correct logical CNOT for [[4,2,2]] by Hadamard-Steane transversality). Result: 2/4 conjugation checks FAIL. *Resolution**: the bridge theorem should target TRANSVERSAL CNOT (`apply CNOT pairwise on qubits (i, i+4) for i = 0..3`), not surgery. The `Code4Code4_CNOT_surgery_schedule` definition remains in the codebase as a SYNTACTIC PLACEHOLDER but is marked NOT a CNOT implementation. See `PyCircuits/qec/code422_surgery_FINDING.md` for full details.
theoremCode4Code4_surgery_schedule_logical_identity
theorem Code4Code4_surgery_schedule_logical_identity :
    ∀ ppm ∈ Code4Code4_CNOT_surgery_schedule,
    ∀ L ∈ Code4Code4_logicals, ppm.commutes_with L = true
*Review finding theorem (Iter 297)**: corollary of the 40-way commutation example above — the surgery schedule's logical- conjugation action on each generator is the IDENTITY, NOT a CNOT. Specifically: for any logical operator L from `Code4Code4_logicals` and any PPM measurement in the schedule, the +1-eigenspace projector `(I + S)/2` of the PPM's stabilizer S commutes with `L.toMatrix`, so the composition `Π_{outcomes} ∘ L.toMatrix = L.toMatrix ∘ Π_{outcomes}` on the full 256-dim space. Restricted to the codespace, this means the surgery's logical-conjugation action is identity. A formally complete proof would require the matrix-level statement: this lemma is stated at the Pauli-algebra level (which is what's actually proved, via `commutes_with = true` above; matrix-level lifting is `PauliString.commutes_of_pointwise` in `LogicalState.lean` plus the iterated projector commutation chain). The review-grade interpretation is the docstring text.
defPauliString.product_of_list
def PauliString.product_of_list (head : PauliString) :
    List PauliString → Pauli.Phase × PauliString
  | [] => (.pos, head)
  | P :: rest =>
      let (φ_acc, R_acc)
Iterate `PauliString.mul` over a list, accumulating the overall phase and resulting Pauli string. Starts from `head` (typically the first PPM's measure string in a schedule).
defCode4Code4_surgery_joint_action
def Code4Code4_surgery_joint_action : Pauli.Phase × PauliString
The 5-PPM CNOT surgery schedule's joint Pauli action, iteratively multiplying each PPM's measure string.
example(example)
example :
    Code4Code4_surgery_joint_action.2 =
      [.Z, .Z, .Z, .Z, .X, .X, .X, .X]
*Concrete computation**: the surgery's joint Pauli action. Decide-checks the explicit result. This is the structural fingerprint of the surgery as a single composite Pauli measurement.
example(example)
example :
    Code4Code4_surgery_joint_action.1 = Pauli.Phase.pos
The joint phase. For the [[4,2,2]] CNOT surgery, all multiplications happen to give .pos phase (the "neutral" sign — each pair of anti-commuting positions cancels in even number).
theoremPauliString.product_of_list_nil
theorem PauliString.product_of_list_nil (head : PauliString) :
    PauliString.product_of_list head [] = (Pauli.Phase.pos, head)
*`product_of_list` empty-list base case** (Iter 124): with no further PauliStrings to multiply, the result is `(.pos, head)`. Direct from the def.
theoremPauliString.product_of_list_singleton
theorem PauliString.product_of_list_singleton (head P : PauliString) :
    PauliString.product_of_list head [P] = PauliString.mul head P
*`product_of_list` singleton case** (Iter 124): with one further PauliString `P`, the result is exactly `head · P` (no phase accumulation beyond `Pauli.mul`'s own). Useful for unfolding surgery sub-products step by step.
theoremPauliString.product_of_list_cons_string
theorem PauliString.product_of_list_cons_string
    (head P : PauliString) (rest : List PauliString) :
    (PauliString.product_of_list head (P :: rest)).2
      = (PauliString.mul (PauliString.product_of_list head rest).2 P).2
*Cons relation for the PauliString component**: the string component of `product_of_list head (P :: rest)` equals the string component of `mul (product_of_list head rest).2 P`. Walks the cons step at the string level only — phases handled by the companion `_phase` lemma.
theoremPauliString.product_of_list_cons_phase
theorem PauliString.product_of_list_cons_phase
    (head P : PauliString) (rest : List PauliString) :
    (PauliString.product_of_list head (P :: rest)).1
      = Pauli.Phase.mul (PauliString.product_of_list head rest).1
          (PauliString.mul (PauliString.product_of_list head rest).2 P).1
*Cons relation for the phase component**: the phase component of `product_of_list head (P :: rest)` equals the accumulated phase `Phase.mul (product_of_list head rest).1 (mul (product_of_list head rest).2 P).1`. Walks the cons step at the phase level only — string handled by the companion `_string` lemma.
theoremPauliString.product_of_list_pair
theorem PauliString.product_of_list_pair (head P Q : PauliString) :
    PauliString.product_of_list head [P, Q]
      = (Pauli.Phase.mul (PauliString.mul head Q).1
            (PauliString.mul (PauliString.mul head Q).2 P).1,
         (PauliString.mul (PauliString.mul head Q).2 P).2)
*2-element forward-walk specialization**: for the surgery- schedule-style list `[P, Q]`, the product evaluates to "head multiplied by Q first, then by P" — i.e., right-to-left. The inner phase is the singleton `mul head Q`'s; the outer phase is from `mul (mul head Q).2 P`.
theoremPauli.mul_self
theorem Pauli.mul_self (p : Pauli) : Pauli.mul p p = (Pauli.Phase.pos, Pauli.I)
Every Pauli is self-inverse: `p · p = (.pos, I)`.
theoremPauliString.mul_self_phase_pos
theorem PauliString.mul_self_phase_pos : ∀ (P : PauliString),
    (PauliString.mul P P).1 = Pauli.Phase.pos
  | [] => rfl
  | p :: ps =>
Phase component of `mul P P` is `.pos` for any PauliString.
theoremPauliString.mul_self_string_eq_id
theorem PauliString.mul_self_string_eq_id : ∀ (P : PauliString),
    (PauliString.mul P P).2 = PauliString.id P.length
  | [] => rfl
  | p :: ps =>
PauliString component of `mul P P` is the identity string at `P.length` qubits: `P · P = (.pos, [I, I, ..., I])`.
defCode4Code4_merge_measure
def Code4Code4_merge_measure : PauliString
*Merge PPM measure as a PauliString** for the conjugation review. Same data as `Code4Code4_merge_CNOT_PPM.measure`, but lifted to a top-level `def` so we can `decide` directly on it.
example(example)
example :
    PauliString.mul Code4Code4_X_L1_left Code4Code4_merge_measure
      = PauliString.mul Code4Code4_merge_measure Code4Code4_X_L1_left
*Direct-product commutation**: `X_L1_left · merge = merge · X_L1_left`. Position-by-position the products are all `.pos` (X·X=I and X·X=I, I·X=X and X·I=X, I·Z=Z and Z·I=Z), so the full multiplication is commutative on this specific pair.
example(example)
example :
    PauliString.mul Code4Code4_X_L1_left Code4Code4_merge_measure
      = (Pauli.Phase.pos,
         [Pauli.I, Pauli.I, Pauli.X, Pauli.X, Pauli.Z, Pauli.Z, Pauli.Z, Pauli.Z])
*Concrete value of the product**: both orderings yield `(.pos, [I, I, X, X, Z, Z, Z, Z])` — the Pauli string with X-on- the-right-of-the-left-patch (qubits 2-3) and Z-on-the-right-patch (qubits 4-7). This is the "merged" version of the X_L1_left operator under the surgery's measurement.
example(example)
example :
    PauliString.product_of_list Code4Code4_X_L1_left [Code4Code4_merge_measure]
      = PauliString.mul Code4Code4_X_L1_left Code4Code4_merge_measure
*`product_of_list` singleton wrapper**: applying `product_of_list X_L1_left [merge_measure]` reduces (via the Iter 124 `product_of_list_singleton` lemma) to `mul X_L1_left merge_measure`, yielding the same Pauli-string result. Demonstrates that the iterated product machinery behaves correctly on a singleton input.
example(example)
example :
    PauliString.mul Code4Code4_X_L1_left Code4Code4_merge_measure
      = PauliString.mul Code4Code4_merge_measure Code4Code4_X_L1_left
    ∧ PauliString.mul Code4Code4_X_L2_left Code4Code4_merge_measure
        = PauliString.mul Code4Code4_merge_measure Code4Code4_X_L2_left
    ∧ PauliString.mul Code4Code4_Z_L1_left Code4Code4_merge_measure
        = PauliString.mul Code4Code4_merge_measure Code4Code4_Z_L1_left
    ∧ PauliString.mul Code4Code4_Z_L2_left Code4Code4_merge_measure
        = PauliString.mul Code4Code4_merge_measure Code4Code4_Z_L2_left
*Four-logical commutation grid via direct product**: for all four left-patch logical operators `{X_L1, X_L2, Z_L1, Z_L2}`, each commutes with the merge PPM measure in the strong sense that left-multiplication and right-multiplication yield the same `(phase, string)` pair. 4 decide-checks.
defCode4Code4_CNOT_image_X_L1
def Code4Code4_CNOT_image_X_L1 : PauliString
*Expected post-surgery image of `X_L1_left`**: by the CNOT conjugation rule, `X_L1` (control X) should copy to `X_L1 · X_R1`. We define this as a top-level def for use in the sorried theorem below.
defCode4Code4_CNOT_image_X_R1
def Code4Code4_CNOT_image_X_R1 : PauliString
*Expected post-surgery image of `X_L1_right`**: by the CNOT conjugation rule, `X_R1` (target X) is unchanged.
defCode4Code4_CNOT_image_Z_L1
def Code4Code4_CNOT_image_Z_L1 : PauliString
*Expected post-surgery image of `Z_L1_left`**: by the CNOT conjugation rule, `Z_L1` (control Z) is unchanged.
defCode4Code4_CNOT_image_Z_R1
def Code4Code4_CNOT_image_Z_R1 : PauliString
*Expected post-surgery image of `Z_L1_right`**: by the CNOT conjugation rule, `Z_R1` (target Z) should copy back to `Z_L1 · Z_R1`.
example(example)
example :
    Code4Code4_CNOT_image_X_L1 = [.X, .X, .I, .I, .X, .X, .I, .I]
*Pauli-algebra concrete check #1**: the image `Code4Code4_CNOT_image_X_L1` evaluates to a specific 8-qubit Pauli string. Decide-witnessed; this anchors the conjugation-rule LHS as a specific list (verifying our def matches expectation).
example(example)
example :
    Code4Code4_CNOT_image_Z_R1 = [.Z, .I, .Z, .I, .Z, .I, .Z, .I]
*Pauli-algebra concrete check #2**: the image `Code4Code4_CNOT_image_Z_R1` evaluates to `[Z, I, Z, I, Z, I, Z, I]`.
theoremTODO_emergent_CNOT_image_X_L1
theorem TODO_emergent_CNOT_image_X_L1 :
    -- Placeholder shape: `apply_surgery (X_L1_left) ≅ X_L1·X_R1`
    -- needs LogicalState + apply_surgery_with_corrections.
    -- For now: the Pauli-algebra shadow holds (decide-checked above).
    Code4Code4_CNOT_image_X_L1
      = (PauliString.mul Code4Code4_X_L1_left Code4Code4_X_L1_right).2
*Phase B emergent-action theorem (statement, parked)**: the 5-PPM CNOT surgery schedule implements logical CNOT_L1,R1 by transforming the X_L1 operator to X_L1 · X_R1. SORRIED until `apply_surgery_with_corrections` infrastructure is added. *The Pauli-algebra shadow** (what we CAN say without the missing primitives): `Code4Code4_CNOT_image_X_L1` equals `mul X_L1_left X_L1_right`'s string component. The emergent- action theorem extends this from "Pauli-multiplication equality" to "operational quantum-state equivalence".
theoremTODO_emergent_CNOT_image_X_R1
theorem TODO_emergent_CNOT_image_X_R1 :
    Code4Code4_CNOT_image_X_R1 = Code4Code4_X_L1_right
*Phase B emergent-action theorem #2**: surgery preserves `X_R1`. Pauli-algebra shadow: `Code4Code4_CNOT_image_X_R1 = X_R1` by definition (no transformation needed for the target's X).
theoremTODO_emergent_CNOT_image_Z_L1
theorem TODO_emergent_CNOT_image_Z_L1 :
    Code4Code4_CNOT_image_Z_L1 = Code4Code4_Z_L1_left
*Phase B emergent-action theorem #3**: surgery preserves `Z_L1`. Pauli-algebra shadow: trivial by def.
theoremTODO_emergent_CNOT_image_Z_R1
theorem TODO_emergent_CNOT_image_Z_R1 :
    Code4Code4_CNOT_image_Z_R1
      = (PauliString.mul Code4Code4_Z_L1_left Code4Code4_Z_L1_right).2
*Phase B emergent-action theorem #4**: surgery copies `Z_R1` back to `Z_L1 · Z_R1`. Pauli-algebra shadow: by def.

FormalRV.PPM.PPMCompilerCorrectness

FormalRV/PPM/PPMCompilerCorrectness.lean
## §1. Abstract realization predicate + COMPOSITION lemma. [VALIDATED] RealizesUpToFrame, realizes_comp, and realizes_comp_id_lower all type-check clean and depend only on [propext, Classical.choice, Quot.sound].
defRealizesUpToFrame
def RealizesUpToFrame {n : Type*} [Fintype n] [DecidableEq n]
    (op frame U : Matrix n n ℂ) : Prop
*Deliverable 1.** Abstract realization predicate: `op` realizes the gate unitary `U` up to a Pauli/Clifford `frame` unitary, meaning `op = frame * U`. Generic over any square-matrix index type `n` (no fixed dimension, no Shor content).
theoremrealizes_comp
theorem realizes_comp {n : Type*} [Fintype n] [DecidableEq n]
    {op1 op2 f1 f2 f1' U1 U2 : Matrix n n ℂ}
    (h1 : RealizesUpToFrame op1 f1 U1)
    (h2 : RealizesUpToFrame op2 f2 U2)
    (hcomm : U2 * f1 = f1' * U2) :
    RealizesUpToFrame (op2 * op1) (f2 * f1') (U2 * U1)
*Deliverable 2 (the heart).** COMPOSITION lemma. If `op1 = f1 * U1` and `op2 = f2 * U2`, and the second gate unitary `U2` commutes through `f1` to a conjugated frame `f1'` (`U2 * f1 = f1' * U2`, the Gottesman/Heisenberg frame-update), then `op2 * op1` realizes `U2 * U1` up to the accumulated frame `f2 * f1'`. Pure matrix algebra; chains by induction (see §2).
theoremrealizes_comp_id_lower
theorem realizes_comp_id_lower {n : Type*} [Fintype n] [DecidableEq n]
    {op1 op2 f2 U1 U2 : Matrix n n ℂ}
    (h1 : RealizesUpToFrame op1 1 U1)
    (h2 : RealizesUpToFrame op2 f2 U2) :
    RealizesUpToFrame (op2 * op1) f2 (U2 * U1)
Convenience corollary (grafted from Design A; validated axiom-clean): trivial LOWER frame (`f1 = 1`) makes the commutation free and the accumulated frame is just `f2`. NOTE the *upper*-frame-trivial analogue is UNSOUND (a `1` upper frame does NOT remove the commutation obligation), so it is omitted.
structurePPMGadgetInterface
structure PPMGadgetInterface (dim : Nat)
Per-gate + frame-conjugation INTERFACE for the PPM compiler at a fixed dimension `dim`. Everything the gate-by-gate induction needs is packed as fields; each is a Clifford/Pauli/lattice-surgery fact about the gadget set, left as an explicit interface so the COMPOSITION is PROVEN modulo it. The composite frame is *built* by the interface as `frame (seq c₁ c₂) = frame c₂ * conj c₂ (frame c₁)`, exactly the shape `realizes_comp` produces, so the seq case closes with no residual goal.
theoremcompileToPPM_correct
theorem compileToPPM_correct {dim : Nat} (Iface : PPMGadgetInterface dim)
    {C : BaseUCom dim} (hC : IsCliffordT C) :
    RealizesUpToFrame (Iface.compile C) (Iface.frame C) (uc_eval C)
*Deliverable 3. The PPM compiler-correctness induction (parametric, no Shor content).** For any Clifford+T circuit `C`, its PPM compilation realizes the circuit's unitary `uc_eval C` up to the accumulated frame — PROVEN by induction on `IsCliffordT`. The base cases are the gadget hypotheses; the `seq` case is the `realizes_comp` COMPOSITION (§1), with the frame conjugation supplied by the interface's `conj_law`. Hence the gate-by-gate composition is fully proven modulo the per-gate gadget interface.
theoremtGadget_realizes_frame
theorem tGadget_realizes_frame
    (U proj corr : Matrix (Fin 4) (Fin 4) ℂ) :
    RealizesUpToFrame (corr * proj * U) (corr * proj) U
*The T-gadget as a `RealizesUpToFrame` instance.** Reusing PPMDenote's `gadgetDenote`/`gadgetDenote_eq`, the flattened gadget operator `corr * proj * U` realizes its interaction unitary `U` up to the measurement-and-correction frame `corr * proj`. Concrete worked instance of the abstract predicate: the gadget's denotation IS `frame * U` on the nose. Stated generically in `(U, proj, corr)` so it covers BOTH T-outcome branches uniformly (outcome 0: `corr = 1`; outcome 1: `corr = Shigh`).
theoremtGadget_denote_eq_frame_apply
theorem tGadget_denote_eq_frame_apply
    (U proj corr : Matrix (Fin 4) (Fin 4) ℂ)
    (ψ res : StateVec 1) :
    FormalRV.PPM.PPMDenote.gadgetDenote U proj corr ψ res
      = ((corr * proj) * U) * (ψ ⊗ᵥ res)
*The T-gadget instance, in `gadgetDenote` form.** The PPMDenote gadget denotation `gadgetDenote U proj corr ψ res` equals the realized operator `(frame * U)` applied to `ψ ⊗ res`, with `frame = corr * proj`. Connects PPMDenote's state-vector denotation directly to the §1 predicate, so the repo's already-proven `tGadget_denote_outcome_0/1` are instances.
theoremrealizes_trivial_frame
theorem realizes_trivial_frame {n : Type*} [Fintype n] [DecidableEq n]
    {op U : Matrix n n ℂ}
    (h : RealizesUpToFrame op (1 : Matrix n n ℂ) U) : op = U
*Frame-trivial realization is exact.** A compilation realizing `U` with frame `1` equals `U` on the nose.
theoremsuccess_transfer
theorem success_transfer {dim : Nat}
    (succ : Square dim → ℝ)
    {compiledOp f : Square dim} {C : BaseUCom dim}
    (hreal : RealizesUpToFrame compiledOp f (uc_eval C))
    (hframe : ∀ U : Square dim, succ (f * U) = succ U) :
    succ compiledOp = succ (uc_eval C)
*Deliverable 4. Transfer skeleton (clean conditional).** Given a success functional `succ : Square dim → ℝ` (probability-of-success as a function of the realized circuit unitary) and an abstract *frame-invariance* hypothesis `hframe` (the success functional is unchanged by the residual Pauli/Clifford frame — operationally: frame-aware post-processing, or a frame trivial on the measured subspace), a compilation realizing `uc_eval C` up to frame `f` has the SAME success probability as the verified circuit. `hframe` is exactly the missing repo lemma (no `uc_eval C₁ = uc_eval C₂ ⇒ equal success`, and no frame-tolerant decoding). Stated as a CONDITIONAL on it rather than assuming it, so the dependency is explicit and the theorem is axiom-free.

FormalRV.PPM.PPMDenote

FormalRV/PPM/PPMDenote.lean
FormalRV.PPM.PPMDenote — first concrete piece of a state-vector denotation ⟦·⟧ for PPM (parallel Pauli-product measurement) programs. ## What this delivers A *compositional operator semantics* (a genuine denotation, not a stub) for measurement-and-correct gadgets at the state-vector level: §1 Primitives. `pauliProj P b` is the projector onto the `b`-eigenspace of a single-qubit Pauli `P` (`b = false ↦ +1`, `b = true ↦ -1`): `(I + (-1)^b P)/2`. `corrOp Q` is the Pauli unitary correction `Q`. Both are built from the repo's `FormalRV.BQCode.Pauli.toMatrix`. §2 Projector algebra (the four PVM laws). `pauliProj` is proved idempotent (`Π² = Π`), Hermitian (`Π† = Π`), the two outcome projectors resolve the identity (`Π₊ + Π₋ = I`) and are orthogonal (`Π₊ Π₋ = 0`) — the four defining laws of a projective measurement. §3 Compositional gadget denotation. `gadgetDenote U proj corr ψ res` = `corr · (proj · (U · (ψ ⊗ res)))`: apply interaction `U`, project the ancilla, apply the data correction — operator semantics for the measurement-and-correct pipeline, with `gadgetDenote_eq` exposing the flattened single-factor form `(corr * proj * U) * (ψ ⊗ res)` (compositionality). Instantiated to the `T`-gadget, REUSING `MagicStateTeleport.t_teleport_outcome_0/1` (whose Born amplitudes are already proven there), to give the headline `⟦T-gadget⟧ = T|ψ⟩` up to a tracked Pauli/Born frame. `tGadget_outcome1_correction_bridge` makes the deferred Pauli/Clifford frame explicit: the raw uncorrected outcome-1 branch maps onto the corrected outcome-1 branch exactly by left-multiplying the KNOWN correction `Shigh`. §4 Single-qubit Clifford gadget = unitary up to frame (Approach B): the `X` correction intertwines the two `Z`-measurement outcomes, `X·Π_{Z=-1} = Π_{Z=+1}·X`, the one-qubit deferred-frame principle, built purely from the general `pauliProj` / `corrOp` primitives. ## Honesty boundary State-vector correctness only (unnormalised post-measurement states). Born-rule scalars (`1/√2`, `ω/√2`) are tracked as frame factors, inherited from `MagicStateTeleport`; outcome *probabilities* are not re-derived here. `§3` gadgets act on the explicit 2-qubit (data ⊗ ancilla) `Fin 4` space using the repo's concrete `projLow0/projLow1/Shigh`. `§4` uses the GENERAL `pauliProj`/`corrOp` 2×2 primitives. Connecting the general `pauliProj` to the concrete `projLow*` via `pad_u`/Kronecker is the natural next step (not attempted here). sorry-free; the key theorems depend only on `propext`, `Classical.choice`, `Quot.sound` (verified by `#print axioms`).
defpauliProj
noncomputable def pauliProj (P : Pauli) (b : Bool) : Matrix (Fin 2) (Fin 2) ℂ
The projector onto the `b`-eigenspace of a single-qubit Pauli `P`: `(I + (-1)^b P)/2`. `b = false ↦ +1` eigenspace, `b = true ↦ -1`. Built from `FormalRV.BQCode.Pauli.toMatrix`.
abbrevcorrOp
abbrev corrOp (Q : Pauli) : Matrix (Fin 2) (Fin 2) ℂ
A Pauli correction operator is the Pauli unitary itself.
theorempauli_conjTranspose
theorem pauli_conjTranspose (P : Pauli) : P.toMatrix.conjTranspose = P.toMatrix
Every single-qubit Pauli matrix is Hermitian: `P† = P`.
theoremsignedPauli_sq
theorem signedPauli_sq (P : Pauli) (b : Bool) :
    (if b then -P.toMatrix else P.toMatrix) * (if b then -P.toMatrix else P.toMatrix)
      = (1 : Matrix (Fin 2) (Fin 2) ℂ)
The signed Pauli `s = (-1)^b P` squares to `I`, since `P² = I`.
theorempauliProj_idem
theorem pauliProj_idem (P : Pauli) (b : Bool) :
    pauliProj P b * pauliProj P b = pauliProj P b
*Idempotency**: `pauliProj P b` is a projector, `Π² = Π`.
theorempauliProj_herm
theorem pauliProj_herm (P : Pauli) (b : Bool) :
    (pauliProj P b).conjTranspose = pauliProj P b
*Hermitian**: `pauliProj P b` is self-adjoint, `Π† = Π`.
theorempauliProj_resolution
theorem pauliProj_resolution (P : Pauli) :
    pauliProj P false + pauliProj P true = (1 : Matrix (Fin 2) (Fin 2) ℂ)
*Resolution of identity**: the two outcome projectors sum to `I`.
theorempauliProj_orthogonal
theorem pauliProj_orthogonal (P : Pauli) :
    pauliProj P false * pauliProj P true = 0
*Orthogonality**: the two outcome projectors annihilate, `Π₊ Π₋ = 0`.
defgadgetDenote
noncomputable def gadgetDenote
    (U proj corr : Matrix (Fin 4) (Fin 4) ℂ) (ψ res : StateVec 1) : StateVec 2
*Compositional denotation of a measurement-and-correct gadget.** Given a 2-qubit (data ⊗ ancilla) interaction unitary `U`, an ancilla measurement projector `proj`, and a data-qubit correction `corr`, the gadget denotes `corr · (proj · (U · (ψ ⊗ res)))`. Operator semantics: apply `U`, project, correct.
theoremgadgetDenote_eq
theorem gadgetDenote_eq
    (U proj corr : Matrix (Fin 4) (Fin 4) ℂ) (ψ res : StateVec 1) :
    gadgetDenote U proj corr ψ res = (corr * proj * U) * (ψ ⊗ᵥ res)
The denotation is **compositional**: each layer is a matrix factor, with associativity collapsing them into a single operator `corr * proj * U`.
theoremtGadget_denote_outcome_0
theorem tGadget_denote_outcome_0 (ψ : StateVec 1) :
    gadgetDenote cnotMatrix projLow0 (1 : Matrix (Fin 4) (Fin 4) ℂ) ψ tKet
      = (1 / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 0 : StateVec 1))
*T-gadget denotation, outcome 0.** The `T` measurement-teleportation gadget (CNOT + Z-measure outcome 0 + no correction) on `ψ ⊗ |T⟩` denotes `(1/√2) • (T|ψ⟩ ⊗ |0⟩)`. Reuses `MagicStateTeleport.t_teleport_outcome_0`.
theoremtGadget_denote_outcome_1
theorem tGadget_denote_outcome_1 (ψ : StateVec 1) :
    gadgetDenote cnotMatrix projLow1 Shigh ψ tKet
      = (ω / Real.sqrt 2 : ℂ) • (Tdata ψ ⊗ᵥ (basisState 1 : StateVec 1))
*T-gadget denotation, outcome 1.** Same gadget, outcome 1, with the deferred Clifford correction `S = Shigh` on the data qubit. Denotes `(ω/√2) • (T|ψ⟩ ⊗ |1⟩)`. Reuses `MagicStateTeleport.t_teleport_outcome_1`.
theoremtGadget_data_outcome_independent
theorem tGadget_data_outcome_independent (ψ : StateVec 1) :
    (∃ c₀ : ℂ, gadgetDenote cnotMatrix projLow0 (1 : Matrix (Fin 4) (Fin 4) ℂ) ψ tKet
        = c₀ • (Tdata ψ ⊗ᵥ (basisState 0 : StateVec 1)))
    ∧ (∃ c₁ : ℂ, gadgetDenote cnotMatrix projLow1 Shigh ψ tKet
        = c₁ • (Tdata ψ ⊗ᵥ (basisState 1 : StateVec 1)))
*Deferred-frame correctness (state-vector level).** Both measurement outcomes of the `T`-gadget produce the *same* data state `Tdata ψ = T|ψ⟩`, differing only by a known frame (scalar `1/√2` vs `ω/√2`, ancilla label `|0⟩` vs `|1⟩`, correction `I` vs `S`). State-vector image of the PPM "outcome-independent operation up to a tracked Pauli/phase frame".
theoremtGadget_outcome1_correction_bridge
theorem tGadget_outcome1_correction_bridge (ψ : StateVec 1) :
    Shigh * gadgetDenote cnotMatrix projLow1 (1 : Matrix (Fin 4) (Fin 4) ℂ) ψ tKet
      = gadgetDenote cnotMatrix projLow1 Shigh ψ tKet
*The deferred Pauli/Clifford frame, explicitly.** The raw (uncorrected) outcome-1 branch — `gadgetDenote` with correction `corr = 1` — is mapped onto the corrected outcome-1 branch exactly by left-multiplying the KNOWN correction `Shigh`. Thus the two outcomes' raw states differ by the known Clifford correction `Shigh`, the deferred-frame byproduct that classical feedforward applies.
theoremclifford_gadget_intertwine
theorem clifford_gadget_intertwine :
    corrOp Pauli.X * pauliProj Pauli.Z true
      = pauliProj Pauli.Z false * corrOp Pauli.X
*Single-qubit Clifford gadget = unitary up to frame.** The Pauli `X` correction intertwines the two `Z`-measurement outcome projectors: `corrOp X * pauliProj Z true = pauliProj Z false * corrOp X`, i.e. `X·Π_{Z=-1} = Π_{Z=+1}·X`. A `Z`-basis measurement gadget whose `-1` branch carries the deferred `X` correction lands in the *same* `+1` eigenspace as the uncorrected `+1` branch — the one-qubit Clifford instance of the deferred-frame principle, built from the general primitives.
theoremclifford_gadget_outcome_independent
theorem clifford_gadget_outcome_independent (ψ : StateVec 1) :
    corrOp Pauli.X * (pauliProj Pauli.Z true * ψ)
      = pauliProj Pauli.Z false * (corrOp Pauli.X * ψ)
*State-vector corollary.** Applying the `X` correction to the `-1`-outcome `Z`-measurement gadget on input `ψ` equals running the `+1`-outcome gadget on the `X`-flipped input `X|ψ⟩`. Fully compositional witness that the corrected gadget is outcome-independent.

FormalRV.PPM.PPMGadgetInstance

FormalRV/PPM/PPMGadgetInstance.lean
FormalRV.PPM.PPMGadgetInstance — an inhabitation witness for `PPMGadgetInterface`. ## READ THIS FIRST — what this module is and is NOT This is the TRIVIAL "unitary baseline" instance: `compile := uc_eval` (the IDENTITY compiler). It proves that `PPMGadgetInterface` is satisfiable and that the composition + transfer machinery of `PPMCompilerCorrectness` actually fires end-to-end — but it does **NOT** model PPM measurement gadgets. Because `compile` is defined to BE `uc_eval`, `realize_gate1`/`realize_cnot` close by `rfl`: the instance asserts "compiling a circuit to its own unitary realizes that unitary", which is true but vacuous. Its only non-trivial content is that `conj` is the GENUINE Heisenberg conjugation `U · f · U⁻¹` (not the unsound identity), so `conj_law` is a real Pauli-frame-update fact. It does NOT discharge the real obligation: a measurement-based instance where `compile (app1 U_T nq)` is the actual T gate-teleportation gadget operator (magic state + CNOT + Z-measure + S-correction), `frame ≠ 1` is the byproduct Pauli, and `realize_gate1` is the THEOREM (from `MagicStateTeleport` / `CliffordPPMRules`) that the gadget realizes the gate up to that frame. That `frame ≠ 1` measurement-based instance — and the interface rework needed to carry the magic/syndrome ancilla qubits — is the genuine open obligation. Kept here as: (1) proof the framework is inhabited / non-vacuous; (2) the exact-frame discharge of `success_transfer` (free, since `frame = 1`), which composes with `ProbabilityTransfer` on the Shor side. Kernel-clean.
defexactFrameInstance
noncomputable def exactFrameInstance (dim : Nat)
    (hinv : ∀ c : BaseUCom dim, Invertible (uc_eval c)) :
    PPMGadgetInterface dim
The exact-frame (`frame = 1`) instance of `PPMGadgetInterface`: the identity compiler `compile := uc_eval`, with GENUINE Heisenberg conjugation `conj c f := U · f · U⁻¹`. `hinv` carries the one physical fact used — every compiled circuit unitary is invertible. TRIVIAL/baseline (see module header): it witnesses inhabitation, it does not model measurements.
theoremexactFrame_compiles_correctly
theorem exactFrame_compiles_correctly (dim : Nat)
    (hinv : ∀ c : BaseUCom dim, Invertible (uc_eval c))
    {C : BaseUCom dim} (hC : IsCliffordT C) :
    (exactFrameInstance dim hinv).compile C = uc_eval C
`compileToPPM_correct` is inhabited (not hypothetical): for any Clifford+T `C`, the exact-frame compilation equals the circuit unitary on the nose. (Baseline — the compiler here IS `uc_eval`.)
theoremexactFrame_success_transfer
theorem exactFrame_success_transfer (dim : Nat)
    (hinv : ∀ c : BaseUCom dim, Invertible (uc_eval c))
    (succ : Square dim → ℝ) {C : BaseUCom dim} (hC : IsCliffordT C) :
    succ ((exactFrameInstance dim hinv).compile C) = succ (uc_eval C)
Success-probability transfer is FREE for the exact-frame instance: the residual frame is `1`, so `success_transfer`'s frame-invariance hypothesis is discharged by `Matrix.one_mul`. Composes with the Shor-side `ProbabilityTransfer` lemmas. (The `frame ≠ 1` case remains open.)

FormalRV.PPM.PPMOperational

FormalRV/PPM/PPMOperational.lean
FormalRV.Framework.PPMOperational — operational semantics of Pauli-Product Measurement on stabilizer states via the Gottesman update algorithm. ## Stabilizer states An n-qubit stabilizer state is specified (up to global phase) by a list of n commuting `PauliString` generators whose group does not contain `-I`. The state itself is the unique simultaneous +1 eigenvector of all generators. Examples: |+⟩ ↔ stabilizer { +X } (1 qubit, 1 generator) |0⟩ ↔ stabilizer { +Z } |Bell⟩ ↔ stabilizer { +XX, +ZZ } (2 qubits, 2 generators) |H⟩ ↔ stabilizer { +XZ, +ZX } (the H-magic state) ## Gottesman PPM update When we measure the Pauli string `P` on a stabilizer state with generators `g_1, …, g_n`: *Case A** — `P` commutes with every `g_i`. Then `±P` is already in the stabilizer group; the measurement outcome is deterministic. The post-measurement state has the same stabilizer. *Case B** — there is some `g_i` with `{P, g_i} = 0`. Choose the first such `g_i`. For every OTHER generator `g_j` (j ≠ i) that also anticommutes with `P`, replace `g_j` with `g_j · g_i` (which now commutes with `P`). Then replace `g_i` itself with `P` (for +1 outcome) or `-P` (for -1 outcome). This is the standard Gottesman algorithm, decidable in pure Bool / Nat / List. ## Post-condition theorems After `apply_PPM_pos`: 1. `P` (with phase +) is in the new stabilizer. 2. All generators in the new state pairwise commute. After `apply_PPM_neg`: 1. `-P` is in the new stabilizer. 2. All generators pairwise commute. Theorems closed on concrete instances by `decide`. No Mathlib. Pure Bool / Nat / List. Decidable.
abbrevStabilizerState
abbrev StabilizerState
A stabilizer state on `n` qubits, represented by an ordered list of `PauliString` generators (each of length `n`). Length and commutation conditions are checked separately via `valid`.
defvalid_length
def valid_length (s : StabilizerState) (n : Nat) : Bool
All generators have the same length `n`.
defvalid_commuting
def valid_commuting (s : StabilizerState) : Bool
All generators pairwise commute.
defvalid
def valid (s : StabilizerState) (n : Nat) : Bool
A `StabilizerState` is structurally well-formed on `n` qubits iff every generator has length `n` AND all generators pairwise commute.
deffind_anticommuting
def find_anticommuting
    (s : StabilizerState) (P : PauliString) : Option Nat
Helper: find the first index of a generator that anticommutes with `P`, or `none` if all commute.
defapply_PPM_pos
def apply_PPM_pos
    (s : StabilizerState) (P : PauliString) : StabilizerState
The Gottesman update for the +1-outcome branch. If no generator anticommutes with `P`, the state's stabilizer is unchanged (the measurement was deterministic — `+P` was already in the stabilizer group, or the implementer's outcome assignment is definitionally consistent). Otherwise, replace the first anticommuting generator with `P`, and for every OTHER anticommuting generator multiply it by the chosen one (so it commutes with `P`).
defapply_PPM_neg
def apply_PPM_neg
    (s : StabilizerState) (P : PauliString) : StabilizerState
The Gottesman update for the -1-outcome branch. Identical to `apply_PPM_pos` except the inserted generator is `-P` rather than `P`.
defplus_state
def plus_state : StabilizerState
|+⟩ state stabilizer: { +X }.
defzero_state
def zero_state : StabilizerState
|0⟩ state stabilizer: { +Z }.
defone_state
def one_state  : StabilizerState
|1⟩ state stabilizer: { -Z }.
theoremPPM_Z_on_plus_pos
theorem PPM_Z_on_plus_pos :
    apply_PPM_pos plus_state ⟨.plus, [.Z]⟩
    = [⟨.plus, [.Z]⟩]
The `Z` measurement on `|+⟩`, +1 outcome, gives `|0⟩`.
theoremPPM_Z_on_plus_neg
theorem PPM_Z_on_plus_neg :
    apply_PPM_neg plus_state ⟨.plus, [.Z]⟩
    = [⟨.minus, [.Z]⟩]
The `Z` measurement on `|+⟩`, -1 outcome, gives `|1⟩`.
theoremPPM_Z_on_zero_pos
theorem PPM_Z_on_zero_pos :
    apply_PPM_pos zero_state ⟨.plus, [.Z]⟩ = zero_state
Measuring Z on |0⟩ is deterministic: the +1 branch preserves the stabilizer (state unchanged).
defbell_state
def bell_state : StabilizerState
|Bell⟩ stabilizer: { +XX, +ZZ }.
theorembell_state_valid
theorem bell_state_valid :
    StabilizerState.valid bell_state 2 = true
theoremPPM_Z1_on_bell_pos
theorem PPM_Z1_on_bell_pos :
    apply_PPM_pos bell_state ⟨.plus, [.Z, .I]⟩
    = [⟨.plus, [.Z, .I]⟩, ⟨.plus, [.Z, .Z]⟩]
Measuring `Z₁` (= Z⊗I) on |Bell⟩ — anticommutes with the XX generator, commutes with ZZ. +1 outcome: replace XX with Z⊗I (the new constraint).
theoremPPM_Z1_on_bell_pos_valid
theorem PPM_Z1_on_bell_pos_valid :
    StabilizerState.valid
      (apply_PPM_pos bell_state ⟨.plus, [.Z, .I]⟩) 2 = true
After the above PPM, the new stabilizer also commutes pairwise — preserved invariant.
theoremPPM_preserves_validity_plus_Z
theorem PPM_preserves_validity_plus_Z :
    StabilizerState.valid
      (apply_PPM_pos plus_state ⟨.plus, [.Z]⟩) 1 = true
theoremPPM_preserves_validity_plus_X
theorem PPM_preserves_validity_plus_X :
    StabilizerState.valid
      (apply_PPM_pos plus_state ⟨.plus, [.X]⟩) 1 = true
theoremPPM_preserves_validity_bell_Z1
theorem PPM_preserves_validity_bell_Z1 :
    StabilizerState.valid
      (apply_PPM_pos bell_state ⟨.plus, [.Z, .I]⟩) 2 = true
theoremPPM_preserves_validity_bell_X2
theorem PPM_preserves_validity_bell_X2 :
    StabilizerState.valid
      (apply_PPM_pos bell_state ⟨.plus, [.I, .X]⟩) 2 = true

FormalRV.PPM.PPMResourceCount

FormalRV/PPM/PPMResourceCount.lean
FormalRV.PPM.PPMResourceCount — resource accounting on the PPM IR. Resource counts are carried on the SAME `QasmOp` IR we emit (`PPMToQASM`) and prove semantically correct (`GadgetChannel`). This is the "resource count after the correctness proof" layer: every count is a pure function of the program, the per-gadget counts are proved by `decide`, and they are ADDITIVE over program concatenation (`*_append`), so the cost of any composed PPM program is the sum of its parts — the parametric formula a full-scale estimate instantiates. ## What is and isn't provable at full RSA-2048 scale (honest) EXACT and proved here: the per-gadget resource vector (logical qubits, magic states consumed, Pauli measurements, Clifford gates, feed-forward corrections) for the T and CCZ teleportation gadgets, and additivity. For the full 2048-bit circuit: the total = (per-component counts, already proved elsewhere, e.g. 462 T / windowed adder) × (the modexp/QFT structure). That whole-circuit assembly is the SAME residual as the semantic side — the full Shor→Clifford+T→PPM program is not assembled gate-by-gate — so a single proved 2048 total is not delivered; the per-gadget vector + additivity ARE. No `sorry`, no new `axiom`.
defisTMagic
def isTMagic : QasmOp → Bool | .opT _ => true | _ => false
`T` magic state consumed (the `|T⟩` prep).
defisCCZMagic
def isCCZMagic : QasmOp → Bool | .opCCZ _ _ _ => true | _ => false
`CCZ` magic state consumed.
defisMeas
def isMeas : QasmOp → Bool | .opMeas _ _ => true | _ => false
Destructive Z-basis (ancilla) measurement.
defisFeedforward
def isFeedforward : QasmOp → Bool
  | .opIf _ _ => true | .opIf2 _ _ _ => true | _ => false
Classically-controlled feed-forward correction (single- or AND-of-two-bit).
defisClifford
def isClifford : QasmOp → Bool
  | .opH _ => true | .opS _ => true | .opX _ => true | .opZ _ => true
  | .opCX _ _ => true | .opCZ _ _ => true | _ => false
A Clifford gate (H/S/X/Z/CX/CZ).
defmaxQubitOf
def maxQubitOf : QasmOp → Nat
  | .opH q | .opT q | .opS q | .opX q | .opZ q => q
  | .opCX a b | .opCZ a b => max a b
  | .opCCZ a b c => max a (max b c)
  | .opMeas q _ => q
  | .opIf _ op | .opIf2 _ _ op => maxQubitOf op
Highest qubit index a single op touches (feed-forward recurses into its body).
defnumTMagic
def numTMagic      (ops : List QasmOp) : Nat
defnumCCZMagic
def numCCZMagic    (ops : List QasmOp) : Nat
defnumMeas
def numMeas        (ops : List QasmOp) : Nat
defnumFeedforward
def numFeedforward (ops : List QasmOp) : Nat
defnumClifford
def numClifford    (ops : List QasmOp) : Nat
defnumQubits
def numQubits      (ops : List QasmOp) : Nat
Logical-qubit count = highest index used + 1.
defseqDepth
def seqDepth       (ops : List QasmOp) : Nat
Sequential-length upper bound on circuit depth (each op one layer).
theoremnumTMagic_append
theorem numTMagic_append (p q : List QasmOp) :
    numTMagic (p ++ q) = numTMagic p + numTMagic q
theoremnumCCZMagic_append
theorem numCCZMagic_append (p q : List QasmOp) :
    numCCZMagic (p ++ q) = numCCZMagic p + numCCZMagic q
theoremnumMeas_append
theorem numMeas_append (p q : List QasmOp) :
    numMeas (p ++ q) = numMeas p + numMeas q
theoremnumFeedforward_append
theorem numFeedforward_append (p q : List QasmOp) :
    numFeedforward (p ++ q) = numFeedforward p + numFeedforward q
theoremnumClifford_append
theorem numClifford_append (p q : List QasmOp) :
    numClifford (p ++ q) = numClifford p + numClifford q
theoremseqDepth_append
theorem seqDepth_append (p q : List QasmOp) :
    seqDepth (p ++ q) = seqDepth p + seqDepth q
theoremtGadget_qubits
theorem tGadget_qubits      : numQubits tGadgetOps = 2
theoremtGadget_TMagic
theorem tGadget_TMagic      : numTMagic tGadgetOps = 1
theoremtGadget_CCZMagic
theorem tGadget_CCZMagic    : numCCZMagic tGadgetOps = 0
theoremtGadget_meas
theorem tGadget_meas        : numMeas tGadgetOps = 1
theoremtGadget_feedforward
theorem tGadget_feedforward : numFeedforward tGadgetOps = 1
theoremtGadget_clifford
theorem tGadget_clifford    : numClifford tGadgetOps = 2
theoremcczGadget_qubits
theorem cczGadget_qubits      : numQubits cczGadgetOps = 6
theoremcczGadget_TMagic
theorem cczGadget_TMagic      : numTMagic cczGadgetOps = 0
theoremcczGadget_CCZMagic
theorem cczGadget_CCZMagic    : numCCZMagic cczGadgetOps = 1
theoremcczGadget_meas
theorem cczGadget_meas        : numMeas cczGadgetOps = 3
theoremcczGadget_feedforward
theorem cczGadget_feedforward : numFeedforward cczGadgetOps = 6
theoremcczGadget_clifford
theorem cczGadget_clifford    : numClifford cczGadgetOps = 6
example(example)
example : numMeas (tGadgetOps ++ cczGadgetOps) = 4
example(example)
example : numTMagic (tGadgetOps ++ cczGadgetOps) = 1
example(example)
example : numCCZMagic (tGadgetOps ++ cczGadgetOps) = 1

FormalRV.PPM.PPMSemanticsGeneral

FormalRV/PPM/PPMSemanticsGeneral.lean
FormalRV.PPM.PPMSemanticsGeneral — GENERAL (parametric) laws of the PPM operational semantics. `PPMOperational` proves its soundness only on concrete instances (`by decide`), and its own header notes that "the general theorem (parametric in s and P) would require induction". For a *general verification framework* the basic-operation semantics must hold for EVERY stabilizer state and EVERY measured Pauli — so a user's arbitrary code + PPM gets the laws for free. This file proves the first such parametric laws, sorry-free: `Pauli.commutes_comm` — single-qubit commutation is symmetric. `Pauli.commutes_mul` — single-qubit bilinearity of commutation over multiplication (the symplectic-form bilinearity). `apply_PPM_pos_length` / `apply_PPM_neg_length` — a PPM preserves the number of stabilizer generators (so the logical dimension / code rank is preserved). `apply_PPM_pos_mem` / `apply_PPM_neg_mem` — projective measurement: when `P` anticommutes with a generator, `±P` becomes a generator of the post-measurement stabilizer (the state is projected onto the corresponding eigenspace). ## Honesty boundary This is the *symbolic stabilizer* (Gottesman tableau) layer; the Gottesman–Knill bridge to ℂ-amplitude state vectors is a separate layer. The remaining general laws — n-qubit `commutes` symmetry, bilinearity of `commutes` over `PauliString.mul`, and full commutativity preservation — build on `Pauli.commutes_mul` (the latter two are gated by `PauliString.mul`'s `foldl`/`let` definition, which resists clean parametric rewriting).
theoremPauli.commutes_comm
theorem Pauli.commutes_comm (a b : Pauli) :
    Pauli.commutes a b = Pauli.commutes b a
theoremPauli.commutes_mul
theorem Pauli.commutes_mul (a b c : Pauli) :
    Pauli.commutes (Pauli.mul a b).2 c
      = (Pauli.commutes a c == Pauli.commutes b c)
theoremapply_PPM_pos_length
theorem apply_PPM_pos_length (s : StabilizerState) (P : PauliString) :
    (apply_PPM_pos s P).length = s.length
theoremapply_PPM_neg_length
theorem apply_PPM_neg_length (s : StabilizerState) (P : PauliString) :
    (apply_PPM_neg s P).length = s.length
theoremapply_PPM_pos_mem
theorem apply_PPM_pos_mem (s : StabilizerState) (P : PauliString) (i : Nat)
    (hi : find_anticommuting s P = some i) (hlt : i < s.length) :
    P ∈ apply_PPM_pos s P
theoremapply_PPM_neg_mem
theorem apply_PPM_neg_mem (s : StabilizerState) (P : PauliString) (i : Nat)
    (hi : find_anticommuting s P = some i) (hlt : i < s.length) :
    P.neg ∈ apply_PPM_neg s P
theoremapply_PPM_outcome_independent_ops
theorem apply_PPM_outcome_independent_ops (s : StabilizerState) (P : PauliString) :
    (apply_PPM_pos s P).map (·.ops) = (apply_PPM_neg s P).map (·.ops)

FormalRV.PPM.PPMShorPipeline

FormalRV/PPM/PPMShorPipeline.lean
===== SECTION 1 / Gadgets (state-vector layer, below FormalRV.Framework) ===== SEAMS 1 + 2: the three gadget families discharge ONE unified predicate (MagicRealizes), and they compose by a List fold that keeps the real gadget operators in the conclusion.
deftrivAnc
noncomputable def trivAnc : StateVec 0
Trivial 1-dim ancilla state (dA = 0); the right unit for ⊗ᵥ.
theoremkron_vec_triv_right
theorem kron_vec_triv_right {a : Nat} (ψ : StateVec a) :
    (ψ ⊗ᵥ trivAnc : StateVec (a + 0)) = ψ
The MISSING b=0 kron law: `ψ ⊗ᵥ trivAnc = ψ`. Enables the Clifford dA=0 case. (Design B repaired the Design-A `unitState0` formulation; this `basisState` form is the one that validates.)
theoremccz_magic_realizes_outcome_000
theorem ccz_magic_realizes_outcome_000 :
    MagicRealizes (dD
(SEAM 1, CCZ instance) The CCZ teleportation gadget, all-zeros (b=000) measurement branch, discharges the SAME `MagicRealizes` predicate as the T gadget. U := the repo's 8T->CCZ `cczMat` (non-axiomatic, tied to the data action by `ccz_gadget_outcome_000_is_cczMat`).
theoremclifford_magic_realizes
theorem clifford_magic_realizes {dD : Nat} (U : Square dD) :
    MagicRealizes (dD
(SEAM 1, Clifford instance) Any Clifford gate discharges `MagicRealizes` with dA = 0, c = 1, G = U: honest Clifford-is-free magic-accounting model (no magic consumed, action exact). NOTE: the T instance is the COMMITTED repo theorem `MagicGadgetInterface.tGadget_magic_realizes (b : Bool)` — reused verbatim, not re-proved here — so {T (any outcome b), CCZ (outcome 000), any Clifford} all satisfy the one predicate.
structureGadget
structure Gadget (dD : Nat)
A gadget bundles the REAL `MagicRealizes` instance together with its data unitary — so the fold below carries genuine gadget content.
deffoldGateProduct
noncomputable def foldGateProduct {dD : Nat} : List (Gadget dD) → Square dD
  | [] => 1
  | g :: gs => foldGateProduct gs * g.U
The data-register product realized by a gadget list (U_n * ... * U_1).
theoremmagic_realizes_list_fold
theorem magic_realizes_list_fold {dD : Nat}
    (gs : List (Gadget dD)) (ψ : StateVec dD) :
    ∃ (final : StateVec dD) (c : ℂ),
      final = c • (foldGateProduct gs * ψ)
      ∧ (∀ (g : Gadget dD) (gtl : List (Gadget dD)), gs = g :: gtl →
          ∃ (anc : StateVec g.dA) (chead : ℂ),
            g.G * (ψ ⊗ᵥ g.magic) = chead • ((g.U * ψ) ⊗ᵥ anc))
(SEAM 2) LIST/FOLD composition, generalising the repo's two-gadget `magic_realizes_chain` over an arbitrary list. The composite data evolution lands the FULL product `foldGateProduct gs * ψ` on the data register (up to one accumulated scalar `c`), AND the conclusion RETAINS the head gadget's actual operator equation — so it is NON-VACUOUS (not the rejected `∃ anc c, True`).
defPPMRealizesShorOracle
def PPMRealizesShorOracle
    (m n anc : Nat) (f_ver f_ppm : Nat → BaseUCom (n + anc)) : Prop
The SINGLE A/B -> C/D seam, named as a definition: the PPM family's effective action on the Shor input state equals the verified circuit's. This is the one obligation blocks A/B must ultimately discharge (see honest_gaps).
theoremppm_preserves_success
theorem ppm_preserves_success
    (a r N m n anc : Nat)
    (f_ver f_ppm : Nat → BaseUCom (n + anc))
    (hppm : PPMRealizesShorOracle m n anc f_ver f_ppm) :
    probability_of_success a r N m n anc f_ppm
      = probability_of_success a r N m n anc f_ver
(SEAM 3, CLOSED by theorem) TRANSFER hookup — EXACT, no error subtraction. `probability_of_success` depends on `f` ONLY through `uc_eval (QPE_var_lsb f)` on the initial state, so a matching effective action preserves success on the nose. Wraps the committed `prob_of_success_congr_via_uc_eval`.
theoremppm_realized_shor_succeeds
theorem ppm_realized_shor_succeeds
    (a r N m bits ainv : Nat)
    (f_ppm : Nat → BaseUCom (bits + ModMul.ancillaWidth bits))
    (h_setting : ShorSetting a r N m bits)
    (h_sizing : CircuitSizing N bits)
    (h_inv : a * ainv % N = 1)
    (hppm : PPMRealizesShorOracle m bits (ModMul.ancillaWidth bits)
              (ModMul.circuitFamily a ainv N bits) f_ppm) :
    probability_of_success a r N m bits (ModMul.ancillaWidth bits) f_ppm
      ≥ κ / (Nat.log2 N : ℝ) ^ 4
(SEAM 4, CLOSED by theorem) THE SINGLE CAUSAL END-TO-END THEOREM (not a conjunction). Success of the PPM-realized circuit is DERIVED THROUGH the realization: `rw [ppm_preserves_success ...]` rewrites PPM success to verified success USING the realization equality `hppm`, THEN `correct_general_via_interface` supplies the bound. Delete `hppm` and the rewrite fails — the realization hypothesis is load-bearing.
theoremppm_realized_shor_succeeds_with_budget
theorem ppm_realized_shor_succeeds_with_budget
    (a r N m bits ainv : Nat)
    (f_ppm : Nat → BaseUCom (bits + ModMul.ancillaWidth bits))
    (h_setting : ShorSetting a r N m bits) (h_sizing : CircuitSizing N bits)
    (h_inv : a * ainv % N = 1)
    (hppm : PPMRealizesShorOracle m bits (ModMul.ancillaWidth bits)
              (ModMul.circuitFamily a ainv N bits) f_ppm)
    (cutoff : ℕ) (p_L num_ops : ℝ) (hp_L : 0 ≤ p_L) (hnum : 0 ≤ num_ops) :
    probability_of_success a r N m bits (ModMul.ancillaWidth bits) f_ppm
      ≥ κ / (Nat.log2 N : ℝ) ^ 4 - (2 * Real.pi / 2 ^ cutoff) - num_ops * p_L
The same causal theorem degraded by the FT union-bound budget (− AQFT cutoff − num_ops·p_L). Derived from the exact form by `linarith`.
theoremppm_shor_succeeds_from_effective_action
theorem ppm_shor_succeeds_from_effective_action
    (a r N m bits ainv : Nat)
    (f_ppm : Nat → BaseUCom (bits + ModMul.ancillaWidth bits))
    (h_setting : ShorSetting a r N m bits) (h_sizing : CircuitSizing N bits)
    (h_inv : a * ainv % N = 1)
    (h_effective_action :
      uc_eval (QPE_var_lsb m (bits + ModMul.ancillaWidth bits) f_ppm)
          (Shor_initial_state m bits (ModMul.ancillaWidth bits))
        = uc_eval (QPE_var_lsb m (bits + ModMul.ancillaWidth bits)
            (ModMul.circuitFamily a ainv N bits))
          (Shor_initial_state m bits (ModMul.ancillaWidth bits))) :
    probability_of_success a r N m bits (ModMul.ancillaWidth bits) f_ppm
The A/B -> C/D obligation made a SINGLE VISIBLE hypothesis (not a hidden gap): given the raw uc_eval-equality, success follows. This is the exact equality blocks A/B must produce to instantiate `ppm_realized_shor_succeeds` with a genuine (non-identity) PPM family.
theoremppm_realized_shor_succeeds_representative
theorem ppm_realized_shor_succeeds_representative
    (a r N m bits ainv : Nat)
    (h_setting : ShorSetting a r N m bits) (h_sizing : CircuitSizing N bits)
    (h_inv : a * ainv % N = 1) :
    probability_of_success a r N m bits (ModMul.ancillaWidth bits)
        (ModMul.circuitFamily a ainv N bits)
      ≥ κ / (Nat.log2 N : ℝ) ^ 4
NON-VACUITY smoke test: the parametric theorem FIRES. The identity realization (f_ppm = the verified family) satisfies the hypothesis by `rfl`. Proves the universally-quantified theorem is not vacuous; a genuinely-different f_ppm needs the residual seam in honest_gaps.

FormalRV.PPM.PPMToQASM

FormalRV/PPM/PPMToQASM.lean
FormalRV.PPM.PPMToQASM — emit OpenQASM 3 from the PPM (Pauli-product measurement) gadget IR. The executable backend of the verified compiler: the same measurement-based gadgets we prove correct (T teleportation in `TGadgetTeleport`, CCZ teleportation in `CCZGadgetTeleport`) are serialised to runnable OpenQASM 3, so the proof (`⟦·⟧`) and an independent numerical Qiskit simulation can be cross-checked (see `PyCircuits/ppm_qasm_verification.py`). Scope: the PPM-LEVEL logical circuit — magic-state prep, the entangling CNOTs, the Z-measurements, and the classically-controlled Clifford corrections (S for T, CZ for CCZ). The physical surface-code / lattice- surgery layer is below this. Pure syntax (no proof obligations).
inductiveQasmOp
inductive QasmOp
A minimal PPM-level QASM instruction set: Clifford+T gates, CNOT/CZ/CCZ, Z-measurement, and a classically-controlled (feed-forward) instruction.
defQasmOp.toLine
def QasmOp.toLine : QasmOp → String
  | .opH q       => s!"h q[{q}];"
  | .opT q       => s!"t q[{q}];"
  | .opS q       => s!"s q[{q}];"
  | .opX q       => s!"x q[{q}];"
  | .opZ q       => s!"z q[{q}];"
  | .opCX c t    => s!"cx q[{c}], q[{t}];"
  | .opCZ a b    => s!"cz q[{a}], q[{b}];"
  -- CCZ is not in stdgates.inc; emit it as H·CCX·H (ccx, h ARE standard).
  | .opCCZ a b c => s!"h q[{c}]; ccx q[{a}], q[{b}], q[{c}]; h q[{c}];"
  | .opMeas q cr => s!"c[{cr}] = measure q[{q}];"
  | .opIf cr op  => s!"if (c[{cr}] == true) " ++ QasmOp.toLine op
One instruction → one OpenQASM 3 line.
deftoQASM
def toQASM (nq ncr : Nat) (ops : List QasmOp) : String
Emit a full OpenQASM 3 program: header + registers + the instruction list.
deftGadgetOps
def tGadgetOps : List QasmOp
deftGadgetQASM
def tGadgetQASM : String
defcczGadgetOps
def cczGadgetOps : List QasmOp
defcczGadgetQASM
def cczGadgetQASM : String

FormalRV.PPM.PPMUpdateInvariants

FormalRV/PPM/PPMUpdateInvariants.lean
FormalRV.Framework.PPMUpdateInvariants — PARAMETRIC correctness invariants for the Gottesman PPM update. `PPMOperational.lean` defines the Gottesman update `apply_PPM_pos/neg` and verifies the "preserves commutativity" invariant only on CONCRETE instances by `decide` (it states at its `:182` that the general theorem "would require induction"). This file closes that gap: the invariants are proven PARAMETRICALLY in the stabilizer state `s` and measured Pauli `P`, for ANY code (the proof is pure PauliString algebra and uses no code-specific structure). This is Level-A lemma A1 of the LDPC-PPM-correctness plan (`notes/topic-ldpc-ppm-correctness.md`): the code-independent foundation the surgery readout theorem (`surgery_extracts_logical`) folds `apply_PPM` over. Main results: `commutes_mul_left` — symplectic bilinearity: commutes (a·b) c = (commutes a c == commutes b c) for equal-length strings. The load-bearing stabilizer fact. `apply_PPM_pos_preserves_valid` / `_neg_` — the Gottesman update preserves the (length + pairwise-commuting) validity invariant. `apply_PPM_pos_inserts_P` — after a non-deterministic measurement, `P` is in the new stabilizer group. No Mathlib. Pure Bool / Nat / List + omega.
theoremfoldl_mul_snd
theorem foldl_mul_snd (l : List (Pauli × Pauli)) (ph0 : Phase) (acc0 : List Pauli) :
    (l.foldl
      (fun (acc : Phase × List Pauli) (ab : Pauli × Pauli) =>
        let (a, b)
The `ops` of a product is the pointwise `zipWith` product of the factor `ops`. The phase accumulator of the fold does not affect the `ops` component.
theoremmul_ops
theorem mul_ops (p q : PauliString) :
    (p.mul q).ops = (p.ops.zip q.ops).map (fun ab => pmul2 ab.1 ab.2)
L1: `(p · q).ops` is the pointwise product over the zipped op lists.
theoremmul_length
theorem mul_length (p q : PauliString) :
    (p.mul q).ops.length = min p.ops.length q.ops.length
theoremmul_length_eq
theorem mul_length_eq (p q : PauliString) (n : Nat)
    (hp : p.ops.length = n) (hq : q.ops.length = n) :
    (p.mul q).ops.length = n
theorempauli_commutes_mul
theorem pauli_commutes_mul (a b c : Pauli) :
    Pauli.commutes (pmul2 a b) c = (Pauli.commutes a c == Pauli.commutes b c)
Single-qubit symplectic bilinearity: commuting with a product is the XNOR of commuting with each factor. 4³ = 64 cases.
theoremcountP_xor_mod2
theorem countP_xor_mod2 {α : Type} (l : List α) (f g : α → Bool) :
    (l.countP (fun x => xor (f x) (g x))) % 2
      = (l.countP f + l.countP g) % 2
Over a single list, the count of positions satisfying the XOR of two predicates is, mod 2, the sum of the two counts.
theoremcommutes_self
theorem commutes_self (p : PauliString) : p.commutes p = true
theoremcommutes_symm
theorem commutes_symm (p q : PauliString) (h : p.ops.length = q.ops.length) :
    p.commutes q = q.commutes p
defantiP
def antiP : Pauli × Pauli → Bool
The single-position anticommutation predicate, as a NAMED constant defdefinitionally equal to the pattern-lambda inside `PauliString.commutes`. Naming it stops `simp` from rewriting it into projection form mid-induction (which would desync the induction hypothesis).
theoremcommutes_eq
theorem commutes_eq (p q : PauliString) :
    p.commutes q = ((p.ops.zip q.ops).countP antiP % 2 == 0)
`commutes` re-expressed through the named `antiP` (defeq, so `rfl`).
theoremadd_mod2_eq
theorem add_mod2_eq (x y : Nat) :
    ((x + y) % 2 == 0) = ((x % 2 == 0) == (y % 2 == 0))
Parity-of-sum to Bool-equality bridge.
theoremantiCount_mul_left
theorem antiCount_mul_left :
    ∀ la lb lc : List Pauli, la.length = lb.length → la.length = lc.length →
      ((((la.zip lb).map (fun ab => pmul2 ab.1 ab.2)).zip lc).countP antiP) % 2
      = ((la.zip lc).countP antiP + (lb.zip lc).countP antiP) % 2
The pointwise anticommutation count is symplectic-bilinear: over equal-length lists, the anti-count of the product against `lc` is mod-2 the sum of the two factors' anti-counts.
theoremcommutes_mul_left
theorem commutes_mul_left (a b c : PauliString)
    (hab : a.ops.length = b.ops.length) (hac : a.ops.length = c.ops.length) :
    (a.mul b).commutes c = (a.commutes c == b.commutes c)
The load-bearing stabilizer fact: a product commutes with `c` iff the two factors agree on whether they commute with `c`.
theoremneg_ops
theorem neg_ops (p : PauliString) : (p.neg).ops = p.ops
`neg` only changes the phase, not the operator list.
theoremneg_commutes_left
theorem neg_commutes_left (p q : PauliString) : (p.neg).commutes q = p.commutes q
`commutes` ignores the global phase, so `neg` on the left is invisible.
theoremneg_commutes_right
theorem neg_commutes_right (p q : PauliString) : q.commutes (p.neg) = q.commutes p
`commutes` ignores the global phase, so `neg` on the right is invisible.
theorempair_commutes
theorem pair_commutes
    (P V g_anti g1 g2 : PauliString) (n : Nat)
    (hP : P.ops.length = n) (hV : V.ops.length = n)
    (hga : g_anti.ops.length = n)
    (h1 : g1.ops.length = n) (h2 : g2.ops.length = n)
    (c12 : g1.commutes g2 = true)
    (cga1 : g_anti.commutes g1 = true)
    (cga2 : g_anti.commutes g2 = true)
    (hgaP : g_anti.commutes P = false)
    (hVcg2 : V.commutes g2 = P.commutes g2)
    (hVcga : V.commutes g_anti = P.commutes g_anti)
    (hg1V : g1.commutes V = g1.commutes P)
The 3×3 commutation case analysis at the heart of the update. Each generator of the new state is the `f`-image of an old generator `g` at position `j`: it is the inserted value `V` (if `j = i_anti`), the generator itself `g` (if it already commutes with `P`), or its product `g · g_anti` (otherwise). This lemma shows ANY two such images commute, using only symplectic bilinearity (`commutes_mul_left`), symmetry, and the facts that `g_anti` anticommutes with `P` while `V` mirrors `P`'s commutation.
theoremapply_generic_valid
theorem apply_generic_valid
    (s : StabilizerState) (P V : PauliString) (n i_anti : Nat) (g_anti : PauliString)
    (hv : StabilizerState.valid s n = true) (hP : P.ops.length = n) (hV : V.ops.length = n)
    (hf : find_anticommuting s P = some i_anti) (hg : s[i_anti]? = some g_anti)
    (hVcomm : ∀ q : PauliString, V.commutes q = P.commutes q)
    (hVcomm' : ∀ q : PauliString, q.commutes V = q.commutes P)
    (hVV : V.commutes V = true)
    (result : StabilizerState)
    (hres : result = (s.zipIdx).map (fun (g, j) =>
              if decide (j = i_anti) then V
              else if g.commutes P then g else g.mul g_anti)) :
    StabilizerState.valid result n = true
The validity-preservation engine, parametric in the inserted operator `V`. `V` must mirror `P`'s commutation behaviour (`hVcomm`/`hVcomm'`) and self-commute (`hVV`); both `P` (the `+` branch) and `P.neg` (the `−` branch) satisfy these because `commutes` is phase-blind.
theoremapply_PPM_pos_preserves_valid
theorem apply_PPM_pos_preserves_valid (s : StabilizerState) (P : PauliString) (n : Nat)
    (hv : StabilizerState.valid s n = true) (hP : P.ops.length = n) :
    StabilizerState.valid (apply_PPM_pos s P) n = true
theoremapply_PPM_neg_preserves_valid
theorem apply_PPM_neg_preserves_valid (s : StabilizerState) (P : PauliString) (n : Nat)
    (hv : StabilizerState.valid s n = true) (hP : P.ops.length = n) :
    StabilizerState.valid (apply_PPM_neg s P) n = true
theoremapply_PPM_pos_inserts_P
theorem apply_PPM_pos_inserts_P (s : StabilizerState) (P : PauliString)
    (h : (find_anticommuting s P).isSome = true) : P ∈ apply_PPM_pos s P
When the measured operator `P` anticommutes with some generator (so the outcome is non-deterministic), the `+` branch of the Gottesman update inserts `P` itself into the new stabilizer group: `P` occupies the `i_anti` slot of `apply_PPM_pos s P`. This is the operational meaning of a stabilizer measurement — `±P` becomes a stabilizer afterwards.

FormalRV.PPM.PauliOps

FormalRV/PPM/PauliOps.lean
FormalRV.Framework.PauliOps — Pauli operators + logical- operator definitions + Pauli-measurement verifier. Per John's directive (2026-05-22): "user needs to provide his definition of all logical Z operators, then we verify that the physical-level implementation is actually that logical operation." This is essential for PPM (logical Pauli measurements): every logical CNOT, S, T-injection, magic-state injection, and many ancillary FT primitives are built from Pauli-product measurements at the physical level. Verification model. USER PROVIDES (in `LogicalOpDef`): - for each logical qubit in a code block, pauli_X = the physical Pauli string we DECLARE to be its logical X pauli_Z = the physical Pauli string we DECLARE to be its logical Z USER ALSO PROVIDES (per claimed measurement): - claimed logical-qubit ID + Pauli kind (X / Z) - the physical PauliString actually measured FRAMEWORK VERIFIES: - the physical PauliString matches the user's declared Pauli for the claimed logical operation. Limitations (v1). Equality is STRICT (list equality). Two physically- equivalent Pauli strings differing by stabilizer multiplication or qubit reordering are NOT yet recognised as the same. A future extension would check equivalence modulo the code's stabilizer group using `QECCode.hx`, `QECCode.hz`.
inductivePauliKind
inductive PauliKind
  | I | X | Y | Z
  deriving Repr, DecidableEq
Single-qubit Pauli factor. `I` is the identity.
structurePauliFactor
structure PauliFactor
A Pauli acting on a specific qubit.
abbrevPauliString
abbrev PauliString
A Pauli string: a list of `PauliFactor`s. Implicit identity on unmentioned qubits. We do NOT require ordering or uniqueness in this v1 representation (a future version may canonicalise).
structureLogicalOpDef
structure LogicalOpDef
The user's declaration of logical X and Z for one logical qubit (identified by its `local_index` in the code block).
structureCodeBlockWithLogicalOps
structure CodeBlockWithLogicalOps
defpauli_string_qubits
def pauli_string_qubits (p : PauliString) : List Nat
defpauli_string_in_atoms
def pauli_string_in_atoms (p : PauliString) (allowed : List Nat) : Bool
defCodeBlockWithLogicalOps.find_op
def CodeBlockWithLogicalOps.find_op
    (block : CodeBlockWithLogicalOps) (local_idx : Nat) :
    Option LogicalOpDef
Look up the `LogicalOpDef` for a given local-index in a block-with-ops.
defverify_logical_pauli_measurement
def verify_logical_pauli_measurement
    (clayout : CodedLogicalLayout)
    (blocks_with_ops : List CodeBlockWithLogicalOps)
    (logical_id : Nat)
    (kind : PauliKind)
    (physical : PauliString) : Bool
A claim: "this physical Pauli string realises a logical Pauli measurement of kind `kind` on logical qubit `logical_id`." Verifier checks: (i) the physical string matches the user's declared `pauli_X` or `pauli_Z` for that logical qubit; (ii) the physical string AND the declared one touch only atoms in the bound block's `physical_qubits`.
structurePauliMeasurementClaim
structure PauliMeasurementClaim

FormalRV.PPM.PauliSemantics

FormalRV/PPM/PauliSemantics.lean
FormalRV.Framework.PauliSemantics — foundational Pauli algebra: `Pauli`, `Phase`, multiplication, commutation, and n-qubit `PauliString`s. Decidable everywhere. Per John's 2026-05-25 directive: > "We need to verify from first principle that some PPM + > classical-controlled Pauli feedback + gate teleportation > + cultivated T state accurately implement logical > circuits up to approximation error + logical error rate. > I doubt that there are still gaps." ## What this file is The framework's prior PPM verifiers were SYNTACTIC: they checked that the implementer's claimed physical Pauli string equals the declared logical operator modulo a stabilizer witness. They did NOT prove the underlying Pauli algebra (that the stabilizer formalism's claims actually hold). This file builds the **first-principle algebraic foundation** — decidable operational Pauli algebra over finite-length n-qubit strings, with global phase tracking ∈ {+1, -1, +i, -i}. ## Pauli algebra facts proved here Pauli multiplication: `X·Y = iZ`, `Y·Z = iX`, `Z·X = iY`, `Y·X = -iZ`, `Z·Y = -iX`, `X·Z = -iY`, and squares = I. Pauli commutation: P commutes with Q iff they're equal, one is I, or they're related by a sign flip. Phase composition: (+1)(+1) = +1, (i)(i) = -1, etc. PauliString commutation: P commutes with Q iff the number of anticommuting POSITIONS is even. No Mathlib. Pure Bool / Nat / List. Decidable. ## Where this fits in the gap closure Closes the foundational gap reported in the 2026-05-25 PPM-semantic review: "no operational link between PauliString and quantum-state action." This file provides the operational Pauli algebra. The next file (`PPMOperational.lean`) provides the stabilizer-update semantics; `CliffordTeleportation.lean` proves a concrete gate-teleportation theorem from those primitives.
inductivePauli
inductive Pauli
defcommutes
def commutes : Pauli → Pauli → Bool
  | .I, _ => true
  | _, .I => true
  | a, b => a == b
Single-qubit Pauli commutation: P commutes with Q iff P = Q, P = I, or Q = I. All other pairs anticommute.
inductivePhase
inductive Phase
defneg
def neg : Phase → Phase
  | .plus    => .minus
  | .minus   => .plus
  | .plus_i  => .minus_i
  | .minus_i => .plus_i
Negate the phase: +1 → -1, +i → -i, etc.
defmul
def mul : Phase → Phase → Phase
  | .plus,     b           => b
  | a,         .plus       => a
  | .minus,    .minus      => .plus
  | .minus,    .plus_i     => .minus_i
  | .minus,    .minus_i    => .plus_i
  | .plus_i,   .minus      => .minus_i
  | .plus_i,   .plus_i     => .minus
  | .plus_i,   .minus_i    => .plus
  | .minus_i,  .minus      => .plus_i
  | .minus_i,  .plus_i     => .plus
  | .minus_i,  .minus_i    => .minus
Phase multiplication. Standard complex-unit arithmetic restricted to fourth roots of unity.
instanceMul
instance : Mul Phase
theoremmul_assoc
theorem mul_assoc (a b c : Phase) : (a * b) * c = a * (b * c)
Sanity: phase multiplication is associative on the fourth-roots of unity (closed by `decide` on the 4³ = 64-case truth table).
theoremmul_plus
theorem mul_plus (a : Phase) : a * .plus = a
Sanity: `+1` is the identity.
theoremplus_mul
theorem plus_mul (a : Phase) : Phase.plus * a = a
defmul
def mul : Pauli → Pauli → Phase × Pauli
  | .I, p => (.plus, p)
  | p, .I => (.plus, p)
  | .X, .X => (.plus, .I)
  | .Y, .Y => (.plus, .I)
  | .Z, .Z => (.plus, .I)
  | .X, .Y => (.plus_i,  .Z)
  | .Y, .X => (.minus_i, .Z)
  | .Y, .Z => (.plus_i,  .X)
  | .Z, .Y => (.minus_i, .X)
  | .Z, .X => (.plus_i,  .Y)
  | .X, .Z => (.minus_i, .Y)
Single-qubit Pauli multiplication. Returns `(phase, P)` such that `P_a · P_b = phase · P`. Standard rules: X·Y = iZ, Y·Z = iX, Z·X = iY, Y·X = -iZ, Z·Y = -iX, X·Z = -iY, P·P = I.
theoremmul_self_is_I
theorem mul_self_is_I (p : Pauli) : (p.mul p).2 = .I
Sanity: Pauli mul agrees with commutes — when P·Q = +Q·P the result is the same I, and when {P, Q} = 0 the phase flips between P·Q and Q·P.
structurePauliString
structure PauliString
instanceBEq
instance : BEq PauliString
defneg
def neg (p : PauliString) : PauliString
Negate the phase.
defidentity
def identity (n : Nat) : PauliString
n-qubit identity.
defcommutes
def commutes (p q : PauliString) : Bool
Two PauliStrings of the same length commute iff the number of POSITIONS where their single-qubit Paulis anticommute is EVEN. This is the classic stabilizer-formalism fact: the global sign change under swap is (−1)^k where k is the anticommuting-position count.
defmul
def mul (p q : PauliString) : PauliString
Pointwise Pauli multiplication, accumulating phase.
instanceMul
instance : Mul PauliString
example(example)
example : Pauli.mul .X .Y = (.plus_i, .Z)
Single-qubit `X · Y = i · Z`.
example(example)
example : Pauli.mul .Y .X = (.minus_i, .Z)
Single-qubit `Y · X = -i · Z` (anticommutation).
example(example)
example : Pauli.mul .X .X = (.plus, .I)
Single-qubit `X · X = +1 · I`.
example(example)
example :
    PauliString.commutes
      ⟨.plus, [.X, .X]⟩ ⟨.plus, [.Z, .Z]⟩ = true
2-qubit string `XX` commutes with `ZZ` (the canonical Bell-pair stabilizers).
example(example)
example :
    PauliString.commutes
      ⟨.plus, [.X, .I]⟩ ⟨.plus, [.Z, .I]⟩ = false
2-qubit string `XI` anticommutes with `ZI`.
example(example)
example :
    PauliString.commutes
      ⟨.plus, [.X, .Z]⟩ ⟨.plus, [.Z, .X]⟩ = true
2-qubit string `XZ` commutes with `ZX` (the canonical H-magic state stabilizers — see CliffordTeleportation).
example(example)
example :
    PauliString.mul ⟨.plus, [.X]⟩ ⟨.plus, [.Y]⟩
    = ⟨.plus_i, [.Z]⟩
`X · Y = iZ` lifted to a 1-qubit PauliString.
example(example)
example :
    PauliString.mul ⟨.plus, [.X, .X]⟩ ⟨.plus, [.Z, .Z]⟩
    = ⟨.minus, [.Y, .Y]⟩
2-qubit: `XX · ZZ = -YY` (the classic minus sign from two anticommutations producing `i · i = -1`).
example(example)
example :
    PauliString.mul (PauliString.identity 1) ⟨.plus, [.X]⟩
    = ⟨.plus, [.X]⟩
Identity is a left/right unit (single qubit).
example(example)
example :
    PauliString.commutes
      ⟨.plus_i, [.X, .Y, .Z]⟩ ⟨.plus_i, [.X, .Y, .Z]⟩ = true
Pauli string commutes with itself iff phase is real (trivially true here since `commutes` only inspects position parity, not phase).

FormalRV.PPM.StabProgram

FormalRV/PPM/StabProgram.lean
FormalRV.PPM.StabProgram — a GENERAL Pauli-measurement program IR with outcome-conditional back-action, and its faithful stabilizer semantics. ## The general framework A user writes ANY PPM program as data: a free `List` of operations meas P — measure the Pauli `P` (records a ±1 outcome), and corr Q — apply the Pauli correction `Q` (the back-action). The semantics `runProgram` interprets a program against a *real* Gottesman stabilizer state: `meas P` takes the `apply_PPM_pos` (outcome +1) or `apply_PPM_neg` (outcome −1) branch according to the supplied outcome bit, and `corr Q` conjugates the stabilizer by `Q` (`applyCorrection`). This is the actual measurement back-action — not a deterministic Boolean stand-in. So a "compiled PPM program implementing a gate" is exactly a `StabProgram` whose `runProgram` realises the gate's action on the stabilizer, for the relevant outcome branches. `CliffordPPMRules`' H and CNOT gadgets are instances, recovered here through the IR. No Hoare logic, no extra machinery — just programs as data + a structural interpreter over the proven `apply_PPM_pos/neg` semantics.
defapplyCorrection
def applyCorrection (Q : PauliString) (s : StabilizerState) : StabilizerState
Apply a Pauli correction `Q` to a stabilizer state: every generator `g` that ANTICOMMUTES with `Q` has its sign flipped (`Q g Q† = −g`); commuting generators are unchanged. This is the classical Pauli-frame back-action of a measurement outcome.
inductiveStabOp
inductive StabOp
  | meas : PauliString → StabOp   -- measure a Pauli (records an outcome)
  | corr : PauliString → StabOp   -- apply a Pauli correction (back-action)
  deriving Repr, Inhabited
One operation of a general stabilizer PPM program.
abbrevStabProgram
abbrev StabProgram
A general PPM program: a free sequence of measurements and corrections. A user can write ANY such program.
defrunProgram
def runProgram : StabProgram → List Bool → StabilizerState → StabilizerState
  | [], _, s => s
  | StabOp.corr Q :: ops, outcomes, s =>
      runProgram ops outcomes (applyCorrection Q s)
  | StabOp.meas P :: ops, [], s =>
      runProgram ops [] (apply_PPM_pos s P)
  | StabOp.meas P :: ops, b :: bs, s =>
      runProgram ops bs (if b then apply_PPM_neg s P else apply_PPM_pos s P)
defhProgram
def hProgram : StabProgram
The H rule as a general PPM program: measure `X_dX_a`, then `Z_dZ_a`.
defcnotProgram
def cnotProgram : StabProgram
The CNOT rule as a general PPM program: measure `Z_cZ_anc`, `X_ancX_t`, then read out the ancilla `Z_anc`.
theoremhProgram_runs_as_gadget
theorem hProgram_runs_as_gadget (s : StabilizerState) :
    runProgram hProgram [false, false] s = hGadget s
Running `hProgram` on the all-`+1` outcome branch is exactly the `CliffordPPMRules.hGadget`.
theoremcnotProgram_runs_as_gadget
theorem cnotProgram_runs_as_gadget (s : StabilizerState) :
    runProgram cnotProgram [false, false, false] s = cnotGadget s
Running `cnotProgram` on the all-`+1` outcome branch is exactly the `CliffordPPMRules.cnotGadget`.
theoremhProgram_truth_table
theorem hProgram_truth_table :
    outputB (runProgram hProgram [false, false] input0)     = some (.plus,  .X)
  ∧ outputB (runProgram hProgram [false, false] input1)     = some (.minus, .X)
  ∧ outputB (runProgram hProgram [false, false] inputPlus)  = some (.plus,  .Z)
  ∧ outputB (runProgram hProgram [false, false] inputMinus) = some (.minus, .Z)
*H, through the general IR.** The user-defined program `hProgram` realises the Hadamard truth table on the stabilizer state.
theoremcnotProgram_truth_table
theorem cnotProgram_truth_table :
    runProgram cnotProgram [false,false,false] cnot_in00
        = [⟨.plus,  [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus,  [.Z,.Z,.Z]⟩]
  ∧ runProgram cnotProgram [false,false,false] cnot_in01
        = [⟨.plus,  [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
  ∧ runProgram cnotProgram [false,false,false] cnot_in10
        = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.plus,  [.Z,.Z,.Z]⟩]
  ∧ runProgram cnotProgram [false,false,false] cnot_in11
        = [⟨.minus, [.Z,.I,.I]⟩, ⟨.plus, [.I,.Z,.I]⟩, ⟨.minus, [.Z,.Z,.Z]⟩]
*CNOT, through the general IR.** The user-defined program `cnotProgram` realises the CNOT truth table on the stabilizer state.
theoremapplyCorrection_length
theorem applyCorrection_length (Q : PauliString) (s : StabilizerState) :
    (applyCorrection Q s).length = s.length
`applyCorrection` flips exactly the signs of anticommuting generators — the defining property of Pauli-frame back-action.
defoutputBPauli
def outputBPauli (s : StabilizerState) : Option Pauli
The output qubit's Pauli *type*, discarding the phase (= the deferred Pauli-frame sign).
theoremhProgram_input0_all_branches
theorem hProgram_input0_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] input0) = some .X
*H, multi-branch (deferred frame).** For BOTH measurement outcomes `(b₁, b₂)`, `H|0⟩` lands in an `X`-eigenstate — the Pauli type is outcome-independent (`X`); only the sign (the frame byproduct) varies.
theoremhProgram_input1_all_branches
theorem hProgram_input1_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] input1) = some .X
`H|1⟩` is an `X`-eigenstate on every outcome branch.
theoremhProgram_inputPlus_all_branches
theorem hProgram_inputPlus_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] inputPlus) = some .Z
`H|+⟩` is a `Z`-eigenstate on every outcome branch.
theoremhProgram_inputMinus_all_branches
theorem hProgram_inputMinus_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] inputMinus) = some .Z
`H|−⟩` is a `Z`-eigenstate on every outcome branch.
theoremsProgram_input0_all_branches
theorem sProgram_input0_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] sInput0) = some .Z
*S, multi-branch (deferred frame).** `S` fixes the `Z`-eigenstates and maps the `X`-eigenstates to `Y`-eigenstates, on EVERY outcome branch (type is outcome-independent; sign is the frame).
theoremsProgram_inputPlus_all_branches
theorem sProgram_inputPlus_all_branches (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] sInputPlus) = some .Y
theoremhProgram_deferred_frame_correct
theorem hProgram_deferred_frame_correct (b₁ b₂ : Bool) :
    outputBPauli (runProgram hProgram [b₁, b₂] input0)     = some .X
  ∧ outputBPauli (runProgram hProgram [b₁, b₂] input1)     = some .X
  ∧ outputBPauli (runProgram hProgram [b₁, b₂] inputPlus)  = some .Z
  ∧ outputBPauli (runProgram hProgram [b₁, b₂] inputMinus) = some .Z
*The deferred-frame H rule, packaged.** Across all four outcome branches and the four basis inputs, the H gadget realises the Hadamard on the output qubit's Pauli *type* (`Z`-eigenstates ↔ `X`-eigenstates); the per-branch sign is the Pauli-frame byproduct, deferred to readout.
theoremcnotProgram_input00_ops_all_branches
theorem cnotProgram_input00_ops_all_branches (b₁ b₂ b₃ : Bool) :
    (runProgram cnotProgram [b₁, b₂, b₃] cnot_in00).map (fun g => g.ops)
      = [[.Z, .I, .I], [.I, .Z, .I], [.Z, .Z, .Z]]
For all 8 outcome branches, `CNOT` on `|00⟩` produces the same output Pauli structure (`Z_c, Z_anc, Z_cZ_ancZ_t`); the signs are the frame.
theoremcnotProgram_input10_ops_all_branches
theorem cnotProgram_input10_ops_all_branches (b₁ b₂ b₃ : Bool) :
    (runProgram cnotProgram [b₁, b₂, b₃] cnot_in10).map (fun g => g.ops)
      = [[.Z, .I, .I], [.I, .Z, .I], [.Z, .Z, .Z]]
Same output Pauli structure for input `|10⟩` — the control bit and all outcome byproducts are carried in the signs (the frame), not the structure.

FormalRV.PPM.StabilizerBasisBridge

FormalRV/PPM/StabilizerBasisBridge.lean
FormalRV.Framework.StabilizerBasisBridge — the Gottesman–Knill bridge FOUNDATION: a computational basis state as a stabilizer state, and the faithfulness of Z-measurement on it. Path A, step (1) foundation (John 2026-06-02). The honest residue between the surgery stabilizer-layer reduction (`SurgeryReduction`) and Shor's Boolean PPM pipeline (`ShorPPMEndToEnd`, whose `MagicBasisPPMState` carries `bits : Nat → Bool`) is the Gottesman–Knill correspondence: computational bits = the +1 computational-basis sector of a stabilizer state. For the basis-PRESERVING modular exponentiation (CNOTs/Toffolis are permutations), the relevant case is the COMPUTATIONAL-BASIS sector — no Hilbert-space superposition machinery is needed. This file builds that core: `encodeBasisState bits n` — |bits⟩ as the stabilizer state `{ (-1)^{bits i} Z_i : i < n }`; `encode_Z_nondisturbing` — measuring ANY Z-product on a basis state is DETERMINISTIC (leaves the stabilizer unchanged) — the Gottesman fact that a Z-measurement on a Z-stabiliser state has a fixed outcome; a readout smoke connecting the measured Z-operator to the bit-parity. ## HONEST SCOPE (this is the FOUNDATION, not the full bridge) This establishes the stabilizer representation of basis states and the determinism of their Z-measurements — the genuine Gottesman–Knill core for the Z-sector. It does NOT, by itself, close the bridge to `ShorPPMEndToEnd`: connecting these stabilizer facts to that file's SPECIFIC `MagicBasisPPMState` CX-macro bit-flip semantics (a particular Clifford encoding, not a clean Z-measurement) is a separate multi-step refinement, and the full-state parametric readout (`row_combination` over the identity matrix) and Hilbert-space faithfulness for superpositions remain out of scope. What is genuinely NEW: the basis state ↔ ±Z-stabiliser encoding and the determinism of Z-measurement on it, code- and size-parametric and axiom-free. No Mathlib. Pure Bool / Nat / List + the PauliString algebra. No `sorry`, no `axiom`.
defindicator
def indicator (i n : Nat) : BoolVec
The length-`n` indicator vector, `true` only at position `i`.
defencodeBasisState
def encodeBasisState (bits : Nat → Bool) (n : Nat) : StabilizerState
A computational basis state `|bits⟩` as a stabilizer state: qubit `i` is stabilised by `(-1)^{bits i} Z_i`.
theoremsignedZRow_commutes_eq
theorem signedZRow_commutes_eq (b : Bool) (l : BoolVec) (q : PauliString) :
    (signedZRow b l).commutes q = (zRow l).commutes q
`commutes` depends only on `.ops`, so a signed Z-row commutes with `q` iff the unsigned `zRow` does.
theoremencode_all_commute_Z
theorem encode_all_commute_Z (bits : Nat → Bool) (n : Nat) (sup : BoolVec) :
    ∀ g ∈ encodeBasisState bits n, g.commutes (zRow sup) = true
Every generator of an encoded basis state commutes with any Z-product `zRow sup` (all generators are Z/I strings; `zRow_commutes`).
theoremencode_Z_nondisturbing
theorem encode_Z_nondisturbing (bits : Nat → Bool) (n : Nat) (sup : BoolVec) :
    apply_PPM_pos (encodeBasisState bits n) (zRow sup) = encodeBasisState bits n
*Determinism of Z-measurement on a basis state.** Measuring any Z-product `zRow sup` on the encoded basis state `|bits⟩` leaves the stabilizer UNCHANGED — the Gottesman fact that a Z-measurement on a Z-stabiliser state has a fixed (deterministic) outcome, with no back-action. This is the genuine bridge core: the computational value of a logical Z-operator is read out without disturbing the (basis) state. Parametric in `n`, `bits`, `sup`; axiom-free.
example(example)
example : StabilizerState.valid (encodeBasisState (fun _ => false) 3) 3 = true
The encoded basis state is a valid stabilizer state (commuting Z generators of length n). Smoke at n = 3 over the four representative bit patterns.
example(example)
example : StabilizerState.valid (encodeBasisState (fun i => decide (i = 1)) 3) 3 = true
example(example)
example :
    apply_PPM_pos (encodeBasisState (fun i => decide (i = 1) || decide (i = 2)) 3)
        (zRow [true, false, true])
      = encodeBasisState (fun i => decide (i = 1) || decide (i = 2)) 3
Readout smoke: on `|bits⟩` with `bits = (0,1,1)`, measuring the Z-product over the support `{0,2}` (qubits 0 and 2) is non-disturbing, and the signed operator the measurement reads is `Z₀Z₂` with sign `(-1)^{bits 0 ⊕ bits 2} = (-1)^{0⊕1} = −1` — i.e. the readout encodes the computational parity.
example(example)
example :
    selectedSignedZProduct [true, false, true]
        [indicator 0 3, indicator 1 3, indicator 2 3] [false, true, true]
      = signedZRow true [true, false, true]
The measured signed Z-operator over `{0,2}` for `bits = (0,1,1)` carries the parity sign `bits 0 ⊕ bits 2 = 0 ⊕ 1 = 1` (−1): the product of the two selected ±Z generators. (`selectedSignedZProduct` over the basis-state generators-as-rows reads the bit-parity — the Z-dual readout structure the surgery uses.)

FormalRV.PPM.TGadgetTeleport

FormalRV/PPM/TGadgetTeleport.lean
FormalRV.PPM.TGadgetTeleport — the REAL T gate-teleportation gadget. The genuine measurement-based T gate (NOT the vacuous `compile := uc_eval` baseline): a real magic ancilla `|T⟩ = tKet` (supplied by the factory — the ONE assumption: we are given `|T⟩` at the port, ideal here; its error rate is the factory parameter), state teleportation: `CNOT` (data controls ancilla) then a `Z`-basis measurement of the ancilla (outcome `b`), classically-controlled feedback: apply the Clifford correction `S = Shigh` to the data qubit iff `b = 1`. The headline `t_gadget_with_feedback` proves that for EVERY outcome `b`, after the feedback the DATA qubit deterministically holds `T|ψ⟩` (the ancilla just collapses to `|b⟩`, with a Born amplitude). Built by reusing the already-proven amplitudes `MagicStateTeleport.t_teleport_outcome_0/1` — kernel-clean, no sorry, no new axiom. This is the worked, non-vacuous per-gate gadget that a real `PPMGadgetInterface` instance must use for the `T` gate.
deftProj
def tProj : Bool → Matrix (Fin 4) (Fin 4) ℂ
  | false => projLow0
  | true  => projLow1
The `Z`-measurement projector on the ancilla for outcome `b`.
deftCorrection
noncomputable def tCorrection : Bool → Matrix (Fin 4) (Fin 4) ℂ
  | false => 1
  | true  => Shigh
The classically-controlled correction: `S` on the data qubit iff outcome `1`.
deftBorn
noncomputable def tBorn : Bool → ℂ
  | false => 1 / Real.sqrt 2
  | true  => ω / Real.sqrt 2
The Born amplitude of outcome `b` (tracked, not normalised away).
deftAnc
noncomputable def tAnc : Bool → StateVec 1
  | false => basisState 0
  | true  => basisState 1
The ancilla's collapsed state after outcome `b`.
theoremt_gadget_with_feedback
theorem t_gadget_with_feedback (ψ : StateVec 1) (b : Bool) :
    tCorrection b * (tProj b * (cnotMatrix * (ψ ⊗ᵥ tKet)))
      = tBorn b • (Tdata ψ ⊗ᵥ tAnc b)
*The real T-gadget with classically-controlled feedback.** For EVERY measurement outcome `b`, running `CNOT`, measuring the ancilla (outcome `b`), and applying the `S` correction iff `b = 1`, on input `ψ ⊗ |T⟩`, yields `(Born amplitude) • (T|ψ⟩ ⊗ |b⟩)`: the data qubit deterministically holds `T|ψ⟩` on BOTH branches (the feedback removes the branch dependence on the data register). Reuses `t_teleport_outcome_0/1`.
theoremt_gadget_data_is_T
theorem t_gadget_data_is_T (ψ : StateVec 1) (b : Bool) :
    ∃ c : ℂ, tCorrection b * (tProj b * (cnotMatrix * (ψ ⊗ᵥ tKet)))
      = c • (Tdata ψ ⊗ᵥ tAnc b)
*The data register always holds `T|ψ⟩`.** Outcome-independent correctness of the corrected gadget: whatever the measurement outcome, after feedback the data state is `T|ψ⟩` (up to the Born amplitude and the ancilla label). This is the real teleportation correctness, deferred-frame discharged by the `S` feedback.

FormalRV.PPM.ToffoliFromCCZ

FormalRV/PPM/ToffoliFromCCZ.lean
FormalRV.PPM.ToffoliFromCCZ — the Clifford reduction `CCX = H·CCZ·H`, turning the 8T→CCZ identity into the actual Toffoli gate, sorry-free. Combined with `EightTToCCZScheme.tDecompMat_eq_cczMat` (the seven-T phase polynomial equals `CCZ`), this proves that the Toffoli unitary is implemented by `H_c · (8T→CCZ) · H_c`, and that its action on a computational basis state is exactly the Boolean Toffoli permutation (flip the target iff both controls are set). ## Technique To avoid `√2` arithmetic inside a 64-entry matrix proof, we factor the Hadamard on the target qubit as `H = (1/√2)·H̄` with `H̄ = [[1,1],[1,-1]]` (integer entries). Then H̄_c · CCZ · H̄_c = 2 · P (P = the Toffoli permutation matrix) is a pure integer/ℂ identity proved by `fin_cases` + `simp`/`norm_num` (no `√2`), and the normalised statement follows by peeling the single scalar fact `(1/√2)² = 1/2`.
defccxPerm
def ccxPerm (k : Fin 8) : Fin 8
The Toffoli permutation on a 3-bit index: swap 6 ↔ 7, else identity.
defccxPermMat
noncomputable def ccxPermMat : Matrix (Fin 8) (Fin 8) ℂ
The Toffoli permutation matrix (8×8 0/1 matrix).
defHbar3
noncomputable def Hbar3 : Matrix (Fin 8) (Fin 8) ℂ
`H̄ = [[1,1],[1,-1]]` applied to the low (target) qubit of a 3-qubit register: `H̄_c (k,k') = [k/2 = k'/2] · H̄(k%2, k'%2)`.
theoremHbar3_ccz_Hbar3
theorem Hbar3_ccz_Hbar3 :
    Hbar3 * cczMat * Hbar3 = (2 : ℂ) • ccxPermMat
defHad3
noncomputable def Had3 : Matrix (Fin 8) (Fin 8) ℂ
The real Hadamard on the target qubit, `H_c = (1/√2)·H̄_c`.
theoreminv_sqrt2_sq
theorem inv_sqrt2_sq : ((1 : ℂ) / Real.sqrt 2) * ((1 : ℂ) / Real.sqrt 2) = 1 / 2
theoremhad_ccz_had_eq_ccxPermMat
theorem had_ccz_had_eq_ccxPermMat :
    Had3 * cczMat * Had3 = ccxPermMat
*`CCX = H_c · CCZ · H_c`.** The Toffoli permutation matrix is the Hadamard-conjugated `CCZ`.
theoremhad_tDecomp_had_eq_ccxPermMat
theorem had_tDecomp_had_eq_ccxPermMat :
    Had3 * tDecompMat * Had3 = ccxPermMat
*8T→CCZ → Toffoli.** The seven-T phase-polynomial gate, conjugated by Hadamards on the target, equals the Toffoli permutation. This is the full chain: 8 T-gates ⟹ CCZ ⟹ (with two Cliffords) Toffoli.
theoremccxPerm_is_boolean_toffoli
theorem ccxPerm_is_boolean_toffoli (k : Fin 8) :
    (aOf (ccxPerm k), bOf (ccxPerm k), cOf (ccxPerm k))
      = (aOf k, bOf k, xor (cOf k) (aOf k && bOf k))
The decode `aOf/bOf/cOf` of `ccxPerm k` realises the Boolean Toffoli update on the three bits: the low bit `c` is flipped iff `a ∧ b`.
theoremccxPermMat_mulVec_basis
theorem ccxPermMat_mulVec_basis (k : Fin 8) :
    ccxPermMat *ᵥ (fun j => if j = k then (1 : ℂ) else 0)
      = (fun i => if i = ccxPerm k then (1 : ℂ) else 0)
The Toffoli permutation matrix sends basis vector `|k⟩` to `|ccxPerm k⟩` — i.e. it permutes computational basis states by the Toffoli map.

FormalRV.PPM.ToffoliScheme

FormalRV/PPM/ToffoliScheme.lean
FormalRV.PPM.ToffoliScheme — a reusable interface for *multiple* provably-correct Toffoli realisations, and the bridge from the quantum gate down to the Boolean `Gate.applyNat (CCX)` semantics that the PPM/arithmetic layer uses. ## What this file delivers (Ask 2) `ToffoliScheme` — an interface whose correctness field is a *theorem** (the gate permutes computational basis states by the Toffoli map), not an abstract contract. Two concrete, sorry-free instances: - `cczTeleportScheme` — one `|CCZ⟩` magic state + Hadamards (the Litinski gate-teleportation route); - `eightTScheme` — the famous **8T→CCZ** seven-T phase polynomial + Hadamards. Both are proved to realise the *same* Toffoli unitary (`Had3 · CCZ · Had3 = Had3 · (8T) · Had3 = ccxPermMat`), differing only in their magic-resource cost. `scheme_implements_gate_applyNat` — the bridge: on the 3-qubit computational basis the realised Toffoli computes exactly `Gate.applyNat (Gate.CCX 0 1 2)`, i.e. it flips the target iff both controls are set. This is the (formerly assumed) Boolean Toffoli action, now *derived* from the quantum gate identity. ## Honesty boundary The proofs are for the 3-qubit Toffoli core (`Fin 8`). The `n`-qubit / arbitrary-control-index version `Gate.applyNat (Gate.CCX a b c)` is the standard identity-tensor embedding of this core on qubits `a,b,c`; that embedding (via `pad_u`/`f_to_vec`) is the remaining plumbing, not new physics. The `|CCZ⟩` magic state's *distillation/cultivation* correctness, and the measurement-outcome Bell step of full gate teleportation, are separate concerns (the latter is the Litinski 64×64 step, left cited). What is proved here is the **unitary gate identity** each scheme realises and its Boolean basis action.
structureToffoliScheme
structure ToffoliScheme
A provably-correct realisation of the 3-qubit Toffoli gate. The `basis_action` field is a theorem: the realised unitary `gate` permutes the computational basis states by the Toffoli map `ccxPerm` (flip the target iff both controls are set).
defcczTeleportScheme
noncomputable def cczTeleportScheme : ToffoliScheme
*Scheme A — CCZ magic-state teleportation.** Consumes one `|CCZ⟩` magic state; the realised gate is `H_c · CCZ · H_c`.
defeightTScheme
noncomputable def eightTScheme : ToffoliScheme
*Scheme B — 8T→CCZ.** Consumes eight `|T⟩` states (the seven-T phase polynomial + catalyst); the realised gate is `H_c · (8T→CCZ) · H_c`.
theoremschemes_realise_same_gate
theorem schemes_realise_same_gate :
    cczTeleportScheme.gate = eightTScheme.gate
Both schemes realise the **same** Toffoli unitary — they differ only in magic-resource accounting.
defbitfun
def bitfun (k : Fin 8) : Nat → Bool
The 3-bit register state encoded by basis index `k`: qubit `0 ↦ a`, `1 ↦ b`, `2 ↦ c` (and `false` elsewhere).
theoremscheme_implements_gate_applyNat
theorem scheme_implements_gate_applyNat (k : Fin 8) :
    bitfun (ccxPerm k) = Gate.applyNat (Gate.CCX 0 1 2) (bitfun k)
*The bridge.** Reading the Toffoli-permuted basis index `ccxPerm k` out in bits is exactly `Gate.applyNat (Gate.CCX 0 1 2)` applied to the bits of `k`. So every `ToffoliScheme` (whose `basis_action` sends `|k⟩` to `|ccxPerm k⟩`) computes the Boolean Toffoli on the 3-qubit register — the action that the PPM layer formerly *assumed* of `teleportCCXRel`.
theoremeightTScheme_implements_boolean_toffoli
theorem eightTScheme_implements_boolean_toffoli (k : Fin 8) :
    bitfun (ccxPerm k) = Gate.applyNat (Gate.CCX 0 1 2) (bitfun k)
Headline: the 8T→CCZ scheme computes the Boolean Toffoli.

FormalRV.PPM.ToffoliSchemeDischarge

FormalRV/PPM/ToffoliSchemeDischarge.lean
FormalRV.PPM.ToffoliSchemeDischarge — discharging the abstract `teleportCCXRel` Toffoli contract in the compiler with the quantum-certified `ToffoliScheme`, for arbitrary n-qubit indices. ## The gap this closes (Ask 2, item 1) `CircuitToPPMToffoliMagic.teleportCCXRel` asserts the bit action `t.bits = Gate.applyNat (Gate.CCX a b c) s.bits` of a Toffoli without quantum justification. `ToffoliScheme` proves the *3-qubit* Toffoli unitary (built from 8T→CCZ or a CCZ magic state) acts on the computational basis by the Toffoli permutation. The key observation that closes the n-qubit gap WITHOUT a heavy non-adjacent state-vector embedding: at the computational-basis / Boolean level, `Gate.applyNat (Gate.CCX a b c)` is *exactly* the local Toffoli on qubits `a,b,c` — it updates only qubit `c` to `c ⊕ (a∧b)` and leaves every other qubit fixed. So the n-qubit bit action is the 3-qubit scheme's certified `tripleAction` reinserted at `(a,b,c)`. Both halves are proved here: `applyNat_CCX_as_tripleAction` — the n-qubit Boolean Toffoli is the local `tripleAction` at qubit `c` (pure Boolean identity). `ccxPerm_certifies_tripleAction` — the `ToffoliScheme`'s quantum gate (via its `basis_action`) realises `tripleAction` on the three qubits (re-expressing `ccxPerm_is_boolean_toffoli`). Composed with the existing `teleportCCXProgram_correct_on_success`, the headline `teleportCCXProgram_realises_scheme_toffoli` shows the compiler's PPM Toffoli output bit-state is exactly the quantum-certified Toffoli — the contract is discharged. ## Honesty boundary This certifies the **computational-basis (Boolean) action**, which is the layer `teleportCCXRel` / the PPM compiler operate on. The full superposition unitarity of the embedded gate (amplitudes on entangled inputs) is the separate `pad_u` story; it is not needed to justify the Boolean PPM model and is not claimed here.
deftripleAction
def tripleAction (a b c : Bool) : Bool × Bool × Bool
The Toffoli's action on a triple of bits `(a, b, c)`: the two controls are preserved, the target is flipped iff both controls are set.
theoremapplyNat_CCX_as_tripleAction
theorem applyNat_CCX_as_tripleAction (a b c : Nat) (f : Nat → Bool) :
    Gate.applyNat (Gate.CCX a b c) f
      = (fun i => if i = c then (tripleAction (f a) (f b) (f c)).2.2 else f i)
`Gate.applyNat (Gate.CCX a b c)` updates only qubit `c`, to the third component of `tripleAction (f a) (f b) (f c)`; every other qubit is untouched. This is the n-qubit Boolean Toffoli expressed as the local triple-action reinserted at `(a,b,c)`.
theoremccxPerm_certifies_tripleAction
theorem ccxPerm_certifies_tripleAction (k : Fin 8) :
    (aOf (ccxPerm k), bOf (ccxPerm k), cOf (ccxPerm k))
      = tripleAction (aOf k) (bOf k) (cOf k)
Reading the `ToffoliScheme`-permuted basis index `ccxPerm k` out in bits yields `tripleAction` of the input bits. This is the quantum certification: by `S.basis_action`, the scheme's unitary sends `|k⟩ → |ccxPerm k⟩`, and that index decodes to the Toffoli image of the input triple.
theoremscheme_realises_tripleAction
theorem scheme_realises_tripleAction (S : ToffoliScheme) (k : Fin 8) :
    S.gate *ᵥ (fun j => if j = k then (1 : ℂ) else 0)
      = (fun i => if i = ccxPerm k then (1 : ℂ) else 0)
    ∧ (aOf (ccxPerm k), bOf (ccxPerm k), cOf (ccxPerm k))
        = tripleAction (aOf k) (bOf k) (cOf k)
Any `ToffoliScheme`'s gate sends `|k⟩` to the basis state whose bits are `tripleAction` of `k`'s bits — i.e. its quantum action *is* the Toffoli on the three qubits.
theoremteleportCCXProgram_realises_scheme_toffoli
theorem teleportCCXProgram_realises_scheme_toffoli
    (F : TFactoryContract) (a b c : Nat)
    (input : Nat → Bool) (s σ' : MagicBasisPPMState)
    (hobs : (magicBasisRefinesApplyNat F).observesBits s input)
    (hrun : MagicPPMProgramRel F (teleportCCXProgram a b c) s σ') :
    (magicBasisRefinesApplyNat F).observesBits σ'
        (fun i => if i = c then (tripleAction (input a) (input b) (input c)).2.2 else input i)
    ∧ (∀ (S : ToffoliScheme) (k : Fin 8),
        S.gate *ᵥ (fun j => if j = k then (1 : ℂ) else 0)
            = (fun i => if i = ccxPerm k then (1 : ℂ) else 0)
          ∧ (aOf (ccxPerm k), bOf (ccxPerm k), cOf (ccxPerm k))
              = tripleAction (aOf k) (bOf k) (cOf k))
*Discharge.** The compiler's `teleportCCXProgram a b c`, run from a state observing `input`, produces an output whose bit-state is the Toffoli's local `tripleAction` reinserted at qubit `c` — and that `tripleAction` is exactly what every `ToffoliScheme`'s quantum gate (8T→CCZ or CCZ magic state) realises. So the formerly-abstract Toffoli bit action is now backed by a proven quantum gate, for arbitrary control/target indices.

FormalRV.PPM.ZXSpiderFusion

FormalRV/PPM/ZXSpiderFusion.lean
FormalRV.Framework.ZX — spider FUSION for the ZX IR, proven to PRESERVE the PPM semantics. Spider fusion is THE core ZX rewrite used to OPTIMIZE lattice surgery (reduce spacetime volume): two same-colour spiders connected by a wire fuse into one spider whose external legs are the symmetric difference of their supports (the shared wire qubit cancels — Z·Z = I, X·X = I). In our PPM grounding (each spider = a Pauli-product measurement, `ZXStabilizer`), fusion is exactly MULTIPLICATION of the measured Paulis: (Z-spider on S₁) ⊕ (Z-spider on S₂) = Z-spider on (S₁ ⊕ S₂), with zRow S₁ · zRow S₂ = zRow (S₁ ⊕ S₂) [`fuseZ_toPauli`] So the fused spider's PPM op measures exactly the PRODUCT of what the two original spiders measured (`fuse_toStabOp`). This makes "verify the OPTIMIZED lattice surgery" a THEOREM — any volume-reducing rewrite built from spider fusion is sound at the PPM layer — rather than a per-instance Stim check. The underlying multiplication algebra is already proven in `SurgeryCorrect` (`signedZRow_mul`, `signedXRow_mul`); here we package it as the ZX fusion rule and connect it to `ZXStabilizer`'s spiders. No Mathlib. No `sorry`, no `axiom`.
deffuse
def fuse (sp1 sp2 : ZXSpider) : ZXSpider
Fuse two same-colour spiders: the external legs are the symmetric difference (`vec_xor`) of the supports — shared wires cancel. Colour from `sp1`.
theoremfuseZ_toPauli
theorem fuseZ_toPauli (S1 S2 : BoolVec) (h : S1.length = S2.length) :
    (zRow S1).mul (zRow S2) = zRow (vec_xor S1 S2)
*Spider fusion, Z-type (Pauli level).** Two Z-spiders fuse by XOR-ing their supports, and the fused Z-row equals the PRODUCT of the two Z-rows.
theoremfuseX_toPauli
theorem fuseX_toPauli (S1 S2 : BoolVec) (h : S1.length = S2.length) :
    (xRow S1).mul (xRow S2) = xRow (vec_xor S1 S2)
*Spider fusion, X-type (Pauli level).**
theoremfuse_toPauli
theorem fuse_toPauli (sp1 sp2 : ZXSpider) (hc : sp1.color = sp2.color)
    (h : sp1.support.length = sp2.support.length) :
    (fuse sp1 sp2).toPauli = (sp1.toPauli).mul (sp2.toPauli)
*Spider fusion PRESERVES PPM semantics.** For two same-colour spiders of equal support length, the fused spider measures exactly the PRODUCT of the two spiders' Paulis: `(fuse sp1 sp2).toPauli = sp1.toPauli · sp2.toPauli`. The ZX fusion rewrite is therefore sound at the PPM layer.
theoremfuse_toStabOp
theorem fuse_toStabOp (sp1 sp2 : ZXSpider) (hc : sp1.color = sp2.color)
    (h : sp1.support.length = sp2.support.length) :
    (fuse sp1 sp2).toStabOp = StabOp.meas ((sp1.toPauli).mul (sp2.toPauli))
*Spider fusion at the PPM-op level.** The fused spider compiles to a single PPM that measures the product of the two original measured Paulis — the rewrite "two spiders → one" is exactly "two measurements → their product".
example(example)
example :
    (fuse { color
Two Z-spiders on `{0,1}` and `{1,2}` fuse to a Z-spider on `{0,2}` (the shared leg 1 cancels) — the canonical merge-product.
example(example)
example :
    (fuse { color
The fused spider's measured Pauli is the product, on a concrete instance.

FormalRV.PPM.ZXStabilizer

FormalRV/PPM/ZXStabilizer.lean
FormalRV.Framework.ZX — ZX calculus as the IR for lattice surgery, grounded in PPM. Strategic design (John 2026-06-02): use ZX calculus as the intermediate representation for lattice surgery, and PROVE it is consistent with our PPM layer. The motivating fact (Tan, Niu & Gidney, "A SAT Scalpel for Lattice Surgery", §II-D: *cube = spider, pipe = wire*): a surface-code lattice-surgery merge IS a ZX spider, and a ZX spider (in the measurement/Clifford fragment) IS a Pauli-product measurement (PPM). So EVERY lattice-surgery implementation — including optimized ones (minimum spacetime volume) — goes through PPM, and is verifiable by reducing its ZX IR to a PPM program and checking it in our already-verified surgery/PPM layer. This module builds the FIRST rung: the phase-free MEASUREMENT FRAGMENT of ZX, where each spider is a Pauli-product measurement, translated to our `StabProgram` PPM IR, and proven to run as the surgery merge state-map `measureChecks`. So: ZX diagram → PPM program → surgery (the user's "all lattice surgery goes through PPM", made into a theorem). ## Roadmap (this is the foundation; full ZX is the program) NOW: spiders-as-PPM (Z-spider = ∏Z measurement, X-spider = ∏X), the ZX→PPM translation, and ZX-merge ↔ surgery-`measureChecks` consistency. NEXT: spider phases (π/2, π, …) for non-Clifford / Y-basis (Tan's `YCube`); spider FUSION and the other ZX rewrite rules, proven to PRESERVE the PPM semantics (so ZX-rewriting = optimization that the framework verifies); general (non-linear) diagrams via a connectivity graph. No Mathlib. Pure List / the PauliString algebra + the Gottesman update. No `sorry`, no `axiom`.
inductiveZXColor
inductive ZXColor | Z | X
  deriving DecidableEq, Repr
A spider's colour: `Z` (green) or `X` (red).
structureZXSpider
structure ZXSpider
A phase-free stabilizer ZX SPIDER as a Pauli-product MEASUREMENT. A Z-spider over `support` measures `∏_{i∈support} Z_i`; an X-spider measures `∏_{i∈support} X_i`. (The full ZX calculus adds non-zero phases and fusion; this is the measurement fragment that realises lattice surgery — Tan §II-D.)
defZXSpider.toPauli
def ZXSpider.toPauli (sp : ZXSpider) : PauliString
The Pauli operator a spider measures (`Z`-spider ↦ `zRow`, `X`-spider ↦ `xRow`).
defZXSpider.toStabOp
def ZXSpider.toStabOp (sp : ZXSpider) : StabOp
The PPM op a spider compiles to: measure its Pauli.
defmkSpider
def mkSpider (color : ZXColor) (idxs : List Nat) (n : Nat) : ZXSpider
Build a spider from its colour and the list of qubit indices in its support (over `n` qubits). Used by the LaSre→PPM importer to emit compact diagrams.
abbrevZXDiagram
abbrev ZXDiagram
A ZX diagram (measurement fragment) — a sequence of spiders.
defzxToPPM
def zxToPPM (d : ZXDiagram) : StabProgram
*ZX → PPM.** Translate a ZX diagram to a PPM program (our `StabProgram` IR): each spider becomes a Pauli-product measurement. This is the formal statement that lattice surgery (as a ZX diagram) GOES THROUGH PPM.
defzxRun
def zxRun (d : ZXDiagram) (s : StabilizerState) : StabilizerState
The ZX diagram's stabilizer semantics = running its PPM realisation on the all-`+1` outcome branch.
defmergeToZX_X
def mergeToZX_X (g : SurgeryGadget) : ZXDiagram
The X-type surgery merge as a ZX diagram: every merged X-check is an X-spider.
defmergeToZX_Z
def mergeToZX_Z (g : SurgeryGadget) : ZXDiagram
The Z-type surgery merge as a ZX diagram: every merged Z-check is a Z-spider.
theoremmergeZX_X_eq_schedule
theorem mergeZX_X_eq_schedule (g : SurgeryGadget) :
    zxToPPM (mergeToZX_X g) = (merged_stabilizers_X g).map StabOp.meas
The X-merge ZX diagram compiles to exactly the surgery X-schedule program.
theoremmergeZX_X_runs_as_surgery
theorem mergeZX_X_runs_as_surgery (g : SurgeryGadget) (s : StabilizerState) :
    zxRun (mergeToZX_X g) s = measureChecks (merged_stabilizers_X g) s
*ZX ↔ PPM ↔ surgery (X-type).** Running the surgery merge's ZX diagram equals the surgery merge state-map `measureChecks` — the lattice surgery, expressed in the ZX IR, reduces to PPM (our verified layer). Axiom-free.
theoremmergeZX_Z_eq_schedule
theorem mergeZX_Z_eq_schedule (g : SurgeryGadget) :
    zxToPPM (mergeToZX_Z g) = (merged_stabilizers_Z g).map StabOp.meas
The Z-merge ZX diagram compiles to exactly the surgery Z-schedule program.
theoremmergeZX_Z_runs_as_surgery
theorem mergeZX_Z_runs_as_surgery (g : SurgeryGadget) (s : StabilizerState) :
    zxRun (mergeToZX_Z g) s = measureChecks (merged_stabilizers_Z g) s
*ZX ↔ PPM ↔ surgery (Z-type).**
example(example)
example (s : StabilizerState) :
    zxRun [{ color