System 1374 declarations in 55 modules
FormalRV.System.Artifacts.CompressedRepeat.AdderRegressions
FormalRV/System/Artifacts/CompressedRepeat/AdderRegressions.lean
Concrete `native_decide` regressions on the n=1 adder block.
Expanded strict bundle at n=10; symbolic acceptance and resource
counts at n=1,000,000 (O(|body|), no expansion); seq2/seq3
Obligation-A instances (96/144 SysCalls); feedback-after-decode at
n=100; ancilla freshness at n=3 and n=10; plus the negative tests
`feedback_bad_body_for_repeat` and `freshness_bad_body_for_repeat`
showing the symbolic checker rejects bad bodies. These ground the
parametric chains; they are not load-bearing for them.
theoremadder_n1_repeated_10_expanded_strict_ok
theorem adder_n1_repeated_10_expanded_strict_ok :
all_invariants_strict_with_slot_capacity_and_freshness_ok
adder_n1_system_models.arch
adder_n1_system_models.opCap
adder_n1_system_models.slotCap
adder_n1_system_models.ancillaModel
(CompressedSchedule.rep 10 (CompressedSchedule.atom adder_n1_syscalls)).expand
adder_n1_system_models.t_react_us
adder_n1_system_models.window_us
adder_n1_system_models.max_per_window = true`n=10` cross-check via expansion + `native_decide`. This
confirms that the strict bundle accepts the EXPANDED
repeated schedule for a moderately large `n`, grounding
the symbolic checker against the existing
expansion-based check.
theoremadder_n1_repeated_1000000_symbolic_ok
theorem adder_n1_repeated_1000000_symbolic_ok :
symbolic_rep_strict_ok
adder_n1_system_models adder_n1_syscalls 1000000 = true*Headline scalability regression**: `n=1_000_000` via
`symbolic_rep_strict_ok`. The symbolic check is
reps-independent by design: it checks the body once
(`O(|body|)`) and never materialises the 1,000,000 SysCall
copies; soundness for the expanded n-fold schedule is
established separately in `SymbolicRepeatSoundness.lean`.
theoremadder_n1_repeated_1000000_resource_wallclock
theorem adder_n1_repeated_1000000_resource_wallclock :
(CompressedSchedule.rep 1000000
(CompressedSchedule.atom adder_n1_syscalls)).resource.wallclock_us
= 48000000Symbolic wallclock for `rep 1_000_000`: `1_000_000 × 48 =
48_000_000` µs. Computed by `CompressedResourceSummary.scale`.
theoremadder_n1_repeated_1000000_resource_gate2q
theorem adder_n1_repeated_1000000_resource_gate2q :
(CompressedSchedule.rep 1000000
(CompressedSchedule.atom adder_n1_syscalls)).resource.gate2q_count
= 18000000Symbolic Gate2q count for `rep 1_000_000`: `1_000_000 × 18
= 18_000_000`.
theoremadder_n1_repeated_1000000_resource_syscall_count
theorem adder_n1_repeated_1000000_resource_syscall_count :
(CompressedSchedule.rep 1000000
(CompressedSchedule.atom adder_n1_syscalls)).resource.syscall_count
= 48000000Symbolic SysCall count for `rep 1_000_000`: `1_000_000 ×
48 = 48_000_000`.
theoremadder_n1_scheduleWithinWallclock
theorem adder_n1_scheduleWithinWallclock :
scheduleWithinWallclock adder_n1_syscalls = truedefadder_seq2
private def adder_seq2 : List SysCall
The composition `seqSchedules adder adder` is 96 SysCalls,
96 µs wallclock.
theoremadder_seq2_length
theorem adder_seq2_length : adder_seq2.length = 96
theoremadder_seq2_wallclock
theorem adder_seq2_wallclock : scheduleWallclockUs adder_seq2 = 96
theoremadder_seq2_exclusivity_ok
theorem adder_seq2_exclusivity_ok :
exclusivity_ok adder_seq2 = truetheoremadder_seq2_factory_exclusivity_ok
theorem adder_seq2_factory_exclusivity_ok :
factory_exclusivity_ok adder_seq2 = truetheoremadder_seq2_operation_capacity_ok
theorem adder_seq2_operation_capacity_ok :
operation_capacity_ok
adder_n1_system_models.opCap adder_seq2 = truetheoremadder_seq2_slot_capacity_ok
theorem adder_seq2_slot_capacity_ok :
slot_capacity_ok
adder_n1_system_models.slotCap adder_seq2 = truetheoremadder_seq2_obligation_A_ok
theorem adder_seq2_obligation_A_ok :
exclusivity_ok adder_seq2 = true
∧ factory_exclusivity_ok adder_seq2 = true
∧ operation_capacity_ok adder_n1_system_models.opCap adder_seq2 = true
∧ slot_capacity_ok adder_n1_system_models.slotCap adder_seq2 = true*Combined Obligation-A status for adder seq2** (concrete
instance, not parametric). All four pairwise / capacity
invariants hold on `seqSchedules adder adder`.
defadder_seq3
private def adder_seq3 : List SysCall
theoremadder_seq3_length
theorem adder_seq3_length : adder_seq3.length = 144
theoremadder_seq3_wallclock
theorem adder_seq3_wallclock : scheduleWallclockUs adder_seq3 = 144
theoremadder_seq3_obligation_A_ok
theorem adder_seq3_obligation_A_ok :
exclusivity_ok adder_seq3 = true
∧ factory_exclusivity_ok adder_seq3 = true
∧ operation_capacity_ok adder_n1_system_models.opCap adder_seq3 = true
∧ slot_capacity_ok adder_n1_system_models.slotCap adder_seq3 = truetheoremadder_repeated_100_feedback_after_decode_ok
theorem adder_repeated_100_feedback_after_decode_ok :
feedback_after_decode_ok
(CompressedSchedule.rep 100 (CompressedSchedule.atom adder_n1_syscalls)).expand
= trueDirect check: `rep 100 adder` expanded passes the
feedback-after-decode invariant.
deffeedback_bad_body_for_repeat
def feedback_bad_body_for_repeat : List SysCall
A bad body: `PauliFrameUpdate 0` at `[0, 1)` BEFORE the
matching `DecodeSyndrome 0` at `[10, 11)` (the review's
counterexample, restated locally to avoid namespace
cycles).
theoremfeedback_bad_body_fails_feedback_check
theorem feedback_bad_body_fails_feedback_check :
feedback_after_decode_ok feedback_bad_body_for_repeat = falsetheoremfeedback_bad_body_repeat_symbolic_rejected
theorem feedback_bad_body_repeat_symbolic_rejected :
symbolic_rep_strict_ok
adder_n1_system_models feedback_bad_body_for_repeat 10 = falsetheoremadder_repeated_3_ancilla_freshness_ok
theorem adder_repeated_3_ancilla_freshness_ok :
ancilla_freshness_ok
adder_n1_system_models.ancillaModel
(CompressedSchedule.rep 3 (CompressedSchedule.atom adder_n1_syscalls)).expand
= trueDirect check: the EXPANDED `rep 3 adder` schedule (144
SysCalls) passes the ancilla-freshness check. Closed by
`native_decide` on the expansion; the parametric chain
(`symbolic_rep_implies_expanded_block_ancilla_freshness_ok`
in `FreshnessSoundness.lean`) covers arbitrary `n`.
theoremadder_repeated_10_ancilla_freshness_ok
theorem adder_repeated_10_ancilla_freshness_ok :
ancilla_freshness_ok
adder_n1_system_models.ancillaModel
(CompressedSchedule.rep 10 (CompressedSchedule.atom adder_n1_syscalls)).expand
= trueDirect check at `n = 10` (480 SysCalls).
deffreshness_bad_body_for_repeat
def freshness_bad_body_for_repeat : List SysCall
A bad body: Gate2q on ancilla site 100 before any
`RequestFreshAncilla` (the review's freshness violator
shape). Body fails ancilla-freshness ⇒ strict bundle
fails ⇒ symbolic_rep_strict_ok rejects.
theoremfreshness_bad_body_fails_freshness_check
theorem freshness_bad_body_fails_freshness_check :
ancilla_freshness_ok
adder_n1_system_models.ancillaModel freshness_bad_body_for_repeat = falsetheoremfreshness_bad_body_repeat_symbolic_rejected
theorem freshness_bad_body_repeat_symbolic_rejected :
symbolic_rep_strict_ok
adder_n1_system_models freshness_bad_body_for_repeat 10 = falseFormalRV.System.Artifacts.CompressedRepeat.CapacitySeq
FormalRV/System/Artifacts/CompressedRepeat/CapacitySeq.lean
Obligation A, sampled-time checks (CLOSED): `operation_capacity_ok`
and `slot_capacity_ok` under shift, `seqSchedules`, n-fold replicate,
and expanded repeat.
Built on `countActiveKindAt` / `activeSitesAt` /
`activeSiteCountInZoneAt` helpers: append distribution, shift
compensation, and out-of-window zero facts. Sample times are
partitioned at the first block's wallclock; each side's per-time
check reduces to the corresponding block's own check. No `sorry`,
no custom `axiom`.
theoremcountActiveKindAt_append
theorem countActiveKindAt_append
(pred : SysCallKind → Bool) (t : Nat) (xs ys : List SysCall) :
countActiveKindAt pred t (xs ++ ys)
= countActiveKindAt pred t xs + countActiveKindAt pred t ystheoremcountActiveKindAt_shiftSchedule
theorem countActiveKindAt_shiftSchedule
(pred : SysCallKind → Bool) (t dt : Nat) (xs : List SysCall) :
countActiveKindAt pred (t + dt) (shiftSchedule dt xs)
= countActiveKindAt pred t xstheoremcountActiveKindAt_eq_zero_of_within_wallclock_at_or_after
theorem countActiveKindAt_eq_zero_of_within_wallclock_at_or_after
(pred : SysCallKind → Bool) (t : Nat) (xs : List SysCall)
(hwithin : scheduleWithinWallclock xs = true)
(h : scheduleWallclockUs xs ≤ t) :
countActiveKindAt pred t xs = 0theoremcountActiveKindAt_shiftSchedule_eq_zero_before_offset
theorem countActiveKindAt_shiftSchedule_eq_zero_before_offset
(pred : SysCallKind → Bool) (t dt : Nat) (ys : List SysCall)
(h : t < dt) :
countActiveKindAt pred t (shiftSchedule dt ys) = 0defop_cap_check_at
private def op_cap_check_at (opCap : OperationCapacityModel)
(L : List SysCall) (t : Nat) : Booltheoremoperation_capacity_ok_eq
private theorem operation_capacity_ok_eq
(opCap : OperationCapacityModel) (L : List SysCall) :
operation_capacity_ok opCap L
= (scheduleEventTimes L).all (op_cap_check_at opCap L)theoremop_cap_check_at_mono
private theorem op_cap_check_at_mono
(opCap : OperationCapacityModel) (L L' : List SysCall) (t : Nat)
(h1 : countActiveKindAt kindIsGate1q t L' ≤ countActiveKindAt kindIsGate1q t L)
(h2 : countActiveKindAt kindIsGate2q t L' ≤ countActiveKindAt kindIsGate2q t L)
(h3 : countActiveKindAt kindIsMeasure t L' ≤ countActiveKindAt kindIsMeasure t L)
(h4 : countActiveKindAt kindIsDecode t L' ≤ countActiveKindAt kindIsDecode t L)
(h5 : countActiveKindAt kindIsFeedback t L' ≤ countActiveKindAt kindIsFeedback t L)
(h6 : countActiveKindAt kindIsMagicReq t L' ≤ countActiveKindAt kindIsMagicReq t L)
(h7 : countActiveKindAt kindIsFreshAnc t L' ≤ countActiveKindAt kindIsFreshAnc t L)
(h8 : countActiveKindAt kindIsTransit t L' ≤ countActiveKindAt kindIsTransit t L)
(hL : op_cap_check_at opCap L t = true) :
op_cap_check_at opCap L' t = trueIf every count in `L'` is ≤ the corresponding count in `L`,
then `L'`'s per-time check passes whenever `L`'s does.
theoremop_cap_check_at_shiftSchedule
private theorem op_cap_check_at_shiftSchedule
(opCap : OperationCapacityModel) (xs : List SysCall) (t dt : Nat) :
op_cap_check_at opCap (shiftSchedule dt xs) (t + dt)
= op_cap_check_at opCap xs ttheoremoperation_capacity_ok_shiftSchedule_eq
theorem operation_capacity_ok_shiftSchedule_eq
(opCap : OperationCapacityModel) (dt : Nat) (xs : List SysCall) :
operation_capacity_ok opCap (shiftSchedule dt xs)
= operation_capacity_ok opCap xstheoremoperation_capacity_ok_seqSchedules
theorem operation_capacity_ok_seqSchedules
(opCap : OperationCapacityModel) (xs ys : List SysCall)
(hxs : operation_capacity_ok opCap xs = true)
(hys : operation_capacity_ok opCap ys = true)
(hwithin : scheduleWithinWallclock xs = true) :
operation_capacity_ok opCap (seqSchedules xs ys) = truetheoremoperation_capacity_ok_seqMany_replicate_block
theorem operation_capacity_ok_seqMany_replicate_block
(opCap : OperationCapacityModel) (block : List SysCall) (n : Nat)
(hblock : operation_capacity_ok opCap block = true)
(hwithin : scheduleWithinWallclock block = true) :
operation_capacity_ok opCap (seqManySchedules (List.replicate n block)) = truetheoremoperation_capacity_ok_repeated_block_expand
theorem operation_capacity_ok_repeated_block_expand
(opCap : OperationCapacityModel) (block : List SysCall) (n : Nat)
(hblock : operation_capacity_ok opCap block = true)
(hwithin : scheduleWithinWallclock block = true) :
operation_capacity_ok opCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremactiveSitesAt_append
theorem activeSitesAt_append (t : Nat) (xs ys : List SysCall) :
activeSitesAt t (xs ++ ys)
= activeSitesAt t xs ++ activeSitesAt t ystheoremactiveSitesAt_shiftSchedule
theorem activeSitesAt_shiftSchedule (t dt : Nat) (xs : List SysCall) :
activeSitesAt (t + dt) (shiftSchedule dt xs) = activeSitesAt t xstheoremactiveSitesAt_eq_nil_of_within_wallclock_at_or_after
theorem activeSitesAt_eq_nil_of_within_wallclock_at_or_after
(t : Nat) (xs : List SysCall)
(hwithin : scheduleWithinWallclock xs = true)
(h : scheduleWallclockUs xs ≤ t) :
activeSitesAt t xs = []theoremactiveSitesAt_shiftSchedule_eq_nil_before_offset
theorem activeSitesAt_shiftSchedule_eq_nil_before_offset
(t dt : Nat) (ys : List SysCall) (h : t < dt) :
activeSitesAt t (shiftSchedule dt ys) = []theoremactiveSiteCountInZoneAt_append
theorem activeSiteCountInZoneAt_append
(z : ZoneCapacitySpec) (t : Nat) (xs ys : List SysCall) :
activeSiteCountInZoneAt z t (xs ++ ys)
= activeSiteCountInZoneAt z t xs + activeSiteCountInZoneAt z t ystheoremactiveSiteCountInZoneAt_shiftSchedule
theorem activeSiteCountInZoneAt_shiftSchedule
(z : ZoneCapacitySpec) (t dt : Nat) (xs : List SysCall) :
activeSiteCountInZoneAt z (t + dt) (shiftSchedule dt xs)
= activeSiteCountInZoneAt z t xstheoremactiveSiteCountInZoneAt_eq_zero_of_within_wallclock_at_or_after
theorem activeSiteCountInZoneAt_eq_zero_of_within_wallclock_at_or_after
(z : ZoneCapacitySpec) (t : Nat) (xs : List SysCall)
(hwithin : scheduleWithinWallclock xs = true)
(h : scheduleWallclockUs xs ≤ t) :
activeSiteCountInZoneAt z t xs = 0theoremactiveSiteCountInZoneAt_shiftSchedule_eq_zero_before_offset
theorem activeSiteCountInZoneAt_shiftSchedule_eq_zero_before_offset
(z : ZoneCapacitySpec) (t dt : Nat) (ys : List SysCall)
(h : t < dt) :
activeSiteCountInZoneAt z t (shiftSchedule dt ys) = 0defslot_cap_check_at
private def slot_cap_check_at (slotCap : SlotCapacityModel)
(L : List SysCall) (t : Nat) : Booltheoremslot_capacity_ok_eq
private theorem slot_capacity_ok_eq
(slotCap : SlotCapacityModel) (L : List SysCall) :
slot_capacity_ok slotCap L
= (scheduleEventTimes L).all (slot_cap_check_at slotCap L)theoremslot_cap_check_at_shiftSchedule
private theorem slot_cap_check_at_shiftSchedule
(slotCap : SlotCapacityModel) (xs : List SysCall) (t dt : Nat) :
slot_cap_check_at slotCap (shiftSchedule dt xs) (t + dt)
= slot_cap_check_at slotCap xs ttheoremslot_capacity_ok_shiftSchedule_eq
theorem slot_capacity_ok_shiftSchedule_eq
(slotCap : SlotCapacityModel) (dt : Nat) (xs : List SysCall) :
slot_capacity_ok slotCap (shiftSchedule dt xs)
= slot_capacity_ok slotCap xstheoremslot_capacity_ok_seqSchedules
theorem slot_capacity_ok_seqSchedules
(slotCap : SlotCapacityModel) (xs ys : List SysCall)
(hxs : slot_capacity_ok slotCap xs = true)
(hys : slot_capacity_ok slotCap ys = true)
(hwithin : scheduleWithinWallclock xs = true) :
slot_capacity_ok slotCap (seqSchedules xs ys) = truetheoremslot_capacity_ok_seqMany_replicate_block
theorem slot_capacity_ok_seqMany_replicate_block
(slotCap : SlotCapacityModel) (block : List SysCall) (n : Nat)
(hblock : slot_capacity_ok slotCap block = true)
(hwithin : scheduleWithinWallclock block = true) :
slot_capacity_ok slotCap (seqManySchedules (List.replicate n block)) = truetheoremslot_capacity_ok_repeated_block_expand
theorem slot_capacity_ok_repeated_block_expand
(slotCap : SlotCapacityModel) (block : List SysCall) (n : Nat)
(hblock : slot_capacity_ok slotCap block = true)
(hwithin : scheduleWithinWallclock block = true) :
slot_capacity_ok slotCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = trueFormalRV.System.Artifacts.CompressedRepeat.CertificateSoundness
FormalRV/System/Artifacts/CompressedRepeat/CertificateSoundness.lean
Recursive compressed-schedule certificate and its soundness.
`compressed_schedule_strict_certificate_ok` accepts `atom` leaves
(strict bundle + within-wallclock + no-magic), `rep n (atom _)`
(via `symbolic_rep_strict_ok_within`), and `seq` of supported
children; `par` and nested `rep` are conservatively rejected. The
mutual soundness theorem carries strict bundle + within-wallclock +
no-magic through `seqSchedules`; the general entry point is
`compressed_schedule_strict_soundness` (consumed by
PPM/QECBridge/LayeredPPMQECInterface). No `sorry`, no custom
`axiom`.
theoremcompressed_schedule_cert_repeated_leaf_eq_symbolic_rep_strict_ok_within
theorem compressed_schedule_cert_repeated_leaf_eq_symbolic_rep_strict_ok_within
(models : SystemModels) (block : List SysCall) (n : Nat) :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.rep n (CompressedSchedule.atom block))
= symbolic_rep_strict_ok_within models block ntheoremcompressed_schedule_cert_repeated_leaf_of_symbolic_rep_strict_ok_within
theorem compressed_schedule_cert_repeated_leaf_of_symbolic_rep_strict_ok_within
(models : SystemModels) (block : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok_within models block n = true) :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.rep n (CompressedSchedule.atom block)) = truetheoremcompressed_schedule_cert_leaf_eq_strict_within_and_no_magic
theorem compressed_schedule_cert_leaf_eq_strict_within_and_no_magic
(models : SystemModels) (block : List SysCall) :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.atom block)
= (all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel block
models.t_react_us models.window_us models.max_per_window
&& scheduleWithinWallclock block
&& decide ((block.filter (fun sc => kindIsMagicReq sc.kind)).length = 0))theoremcompressed_schedule_strict_soundness_repeated_leaf
theorem compressed_schedule_strict_soundness_repeated_leaf
(models : SystemModels) (block : List SysCall) (n : Nat)
(hCert :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.rep n (CompressedSchedule.atom block)) = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand
models.t_react_ustheoremcompressed_schedule_strict_soundness_leaf
theorem compressed_schedule_strict_soundness_leaf
(models : SystemModels) (block : List SysCall)
(hCert :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.atom block) = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.atom block).expand
models.t_react_ustheoremfoldl_max_end_us_ge_acc
private theorem foldl_max_end_us_ge_acc
(xs : List SysCall) (acc : Nat) :
acc ≤ xs.foldl (fun a s => Nat.max a s.end_us) acctheoremfoldl_max_end_us_ge_of_mem
private theorem foldl_max_end_us_ge_of_mem
(xs : List SysCall) (sc : SysCall) (h : sc ∈ xs) (acc : Nat) :
sc.end_us ≤ xs.foldl (fun a s => Nat.max a s.end_us) acctheoremend_us_le_scheduleWallclockUs
theorem end_us_le_scheduleWallclockUs
(xs : List SysCall) (sc : SysCall) (h : sc ∈ xs) :
sc.end_us ≤ scheduleWallclockUs xstheoremscheduleWithinWallclock_seqSchedules
theorem scheduleWithinWallclock_seqSchedules
(xs ys : List SysCall)
(hxs : scheduleWithinWallclock xs = true)
(hys : scheduleWithinWallclock ys = true) :
scheduleWithinWallclock (seqSchedules xs ys) = truetheoremscheduleWithinWallclock_seqMany_replicate_block
theorem scheduleWithinWallclock_seqMany_replicate_block
(block : List SysCall) (n : Nat)
(hblock : scheduleWithinWallclock block = true) :
scheduleWithinWallclock (seqManySchedules (List.replicate n block)) = truetheoremscheduleWithinWallclock_repeated_block_expand
theorem scheduleWithinWallclock_repeated_block_expand
(block : List SysCall) (n : Nat)
(hblock : scheduleWithinWallclock block = true) :
scheduleWithinWallclock
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremmagic_count_seqSchedules
theorem magic_count_seqSchedules (xs ys : List SysCall) :
((seqSchedules xs ys).filter (fun sc => kindIsMagicReq sc.kind)).length
= (xs.filter (fun sc => kindIsMagicReq sc.kind)).length
+ (ys.filter (fun sc => kindIsMagicReq sc.kind)).lengththeoremwindow_throughput_ok_seqSchedules_of_no_magic
theorem window_throughput_ok_seqSchedules_of_no_magic
(xs ys : List SysCall) (window_us max_per_window : Nat)
(hxs : (xs.filter (fun sc => kindIsMagicReq sc.kind)).length = 0)
(hys : (ys.filter (fun sc => kindIsMagicReq sc.kind)).length = 0) :
window_throughput_ok (seqSchedules xs ys) window_us max_per_window = truetheoremall_invariants_strict_with_slot_capacity_and_freshness_ok_seqSchedules
theorem all_invariants_strict_with_slot_capacity_and_freshness_ok_seqSchedules
(models : SystemModels) (xs ys : List SysCall)
(hxs :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel xs
models.t_react_us models.window_us models.max_per_window = true)
(hys :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel ys
models.t_react_us models.window_us models.max_per_window = true)
(hwithin_xs : scheduleWithinWallclock xs = true)
(hnoMagic_xs :theoremexpand_seq_cons
theorem expand_seq_cons (c : CompressedSchedule) (rest : List CompressedSchedule) :
(CompressedSchedule.seq (c :: rest)).expand
= seqSchedules c.expand (CompressedSchedule.seq rest).expandtheoremstrict_bundle_empty
theorem strict_bundle_empty (models : SystemModels) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel
[]
models.t_react_us models.window_us models.max_per_window = trueStrict bundle is trivially true on the empty schedule.
theoremscheduleWithinWallclock_empty
theorem scheduleWithinWallclock_empty :
scheduleWithinWallclock ([] : List SysCall) = truetheoremmagic_count_empty
theorem magic_count_empty :
(([] : List SysCall).filter (fun sc => kindIsMagicReq sc.kind)).length = 0theoremcompressed_schedule_strict_soundness_seq
theorem compressed_schedule_strict_soundness_seq
(models : SystemModels) (children : List CompressedSchedule)
(hCert :
compressed_schedule_strict_certificate_ok models
(CompressedSchedule.seq children) = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.seq children).expand
models.t_react_ustheoremcompressed_schedule_strict_soundness
theorem compressed_schedule_strict_soundness
(models : SystemModels) (cs : CompressedSchedule)
(hCert : compressed_schedule_strict_certificate_ok models cs = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
cs.expand
models.t_react_us
models.window_us
models.max_per_window = trueFormalRV.System.Artifacts.CompressedRepeat.ExclusivitySeq
FormalRV/System/Artifacts/CompressedRepeat/ExclusivitySeq.lean
Obligation A, pairwise checks (CLOSED): `exclusivity_ok` and
`factory_exclusivity_ok` under shift, `seqSchedules`, n-fold
replicate, and expanded repeat.
Both chains use the pair-check abstraction (`excl_pair_check`,
`factory_excl_pair_check`), `shiftSchedule_getElem?` index threading,
same-block/cross-block index decomposition, and
`cross_pair_no_overlap` for the cross-boundary pairs. The
`scheduleWithinWallclock` hypothesis (strict-positive durations) is
the structural input. No `sorry`, no custom `axiom`.
theoremshiftSchedule_length
theorem shiftSchedule_length (dt : Nat) (xs : List SysCall) :
(shiftSchedule dt xs).length = xs.lengththeoremshiftSchedule_getElem?
theorem shiftSchedule_getElem? (dt : Nat) (xs : List SysCall) (i : Nat) :
(shiftSchedule dt xs)[i]? = Option.map (shiftSysCall dt) (xs[i]?)theoremexclusivity_pair_eq_shift
private theorem exclusivity_pair_eq_shift
(dt : Nat) (xs : List SysCall) (i j : Nat) :
(match (shiftSchedule dt xs)[i]?, (shiftSchedule dt xs)[j]? with
| some s_i, some s_j =>
if intervals_overlap s_i.begin_us s_i.end_us
s_j.begin_us s_j.end_us = true then
atoms_disjoint (syscall_acts_on s_i) (syscall_acts_on s_j)
else true
| _, _ => true)
= (match xs[i]?, xs[j]? with
| some s_i, some s_j =>
if intervals_overlap s_i.begin_us s_i.end_ustheoremexclusivity_ok_shiftSchedule_eq
theorem exclusivity_ok_shiftSchedule_eq (dt : Nat) (xs : List SysCall) :
exclusivity_ok (shiftSchedule dt xs) = exclusivity_ok xsdefexcl_pair_check
private def excl_pair_check (L : List SysCall) (i j : Nat) : Bool
theoremexclusivity_ok_of_pair_check
private theorem exclusivity_ok_of_pair_check (L : List SysCall)
(h : ∀ i j, i < j → j < L.length → excl_pair_check L i j = true) :
exclusivity_ok L = truetheoremexcl_pair_check_of_exclusivity_ok
private theorem excl_pair_check_of_exclusivity_ok (L : List SysCall)
(hL : exclusivity_ok L = true) (i j : Nat) (hij : i < j) (hj : j < L.length) :
excl_pair_check L i j = truetheoremexcl_pair_check_shiftSchedule
private theorem excl_pair_check_shiftSchedule
(dt : Nat) (L : List SysCall) (i j : Nat) :
excl_pair_check (shiftSchedule dt L) i j = excl_pair_check L i jtheoremexclusivity_ok_seqSchedules
theorem exclusivity_ok_seqSchedules
(xs ys : List SysCall)
(hxs : exclusivity_ok xs = true)
(hys : exclusivity_ok ys = true)
(hwithin : scheduleWithinWallclock xs = true) :
exclusivity_ok (seqSchedules xs ys) = truetheoremexclusivity_ok_seqMany_replicate_block
theorem exclusivity_ok_seqMany_replicate_block
(block : List SysCall) (n : Nat)
(hblock : exclusivity_ok block = true)
(hwithin : scheduleWithinWallclock block = true) :
exclusivity_ok (seqManySchedules (List.replicate n block)) = true`exclusivity_ok` survives sequential composition of `n`
identical blocks via `seqManySchedules (List.replicate n
block)`, provided the block is within-wallclock and
exclusive on its own. By induction on `n`.
theoremexclusivity_ok_repeated_block_expand
theorem exclusivity_ok_repeated_block_expand
(block : List SysCall) (n : Nat)
(hblock : exclusivity_ok block = true)
(hwithin : scheduleWithinWallclock block = true) :
exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremfactory_exclusivity_pair_eq_shift
private theorem factory_exclusivity_pair_eq_shift
(dt : Nat) (xs : List SysCall) (i j : Nat) :
(match (shiftSchedule dt xs)[i]?, (shiftSchedule dt xs)[j]? with
| some s_i, some s_j =>
if intervals_overlap s_i.begin_us s_i.end_us
s_j.begin_us s_j.end_us = true then
atoms_disjoint (syscall_factory_claims s_i)
(syscall_factory_claims s_j)
else true
| _, _ => true)
= (match xs[i]?, xs[j]? with
| some s_i, some s_j =>theoremfactory_exclusivity_ok_shiftSchedule_eq
theorem factory_exclusivity_ok_shiftSchedule_eq (dt : Nat) (xs : List SysCall) :
factory_exclusivity_ok (shiftSchedule dt xs) = factory_exclusivity_ok xsdeffactory_excl_pair_check
private def factory_excl_pair_check (L : List SysCall) (i j : Nat) : Bool
theoremfactory_exclusivity_ok_of_pair_check
private theorem factory_exclusivity_ok_of_pair_check (L : List SysCall)
(h : ∀ i j, i < j → j < L.length → factory_excl_pair_check L i j = true) :
factory_exclusivity_ok L = truetheoremfactory_excl_pair_check_of_factory_exclusivity_ok
private theorem factory_excl_pair_check_of_factory_exclusivity_ok
(L : List SysCall) (hL : factory_exclusivity_ok L = true)
(i j : Nat) (hij : i < j) (hj : j < L.length) :
factory_excl_pair_check L i j = truetheoremfactory_excl_pair_check_shiftSchedule
private theorem factory_excl_pair_check_shiftSchedule
(dt : Nat) (L : List SysCall) (i j : Nat) :
factory_excl_pair_check (shiftSchedule dt L) i j
= factory_excl_pair_check L i jtheoremfactory_exclusivity_ok_seqSchedules
theorem factory_exclusivity_ok_seqSchedules
(xs ys : List SysCall)
(hxs : factory_exclusivity_ok xs = true)
(hys : factory_exclusivity_ok ys = true)
(hwithin : scheduleWithinWallclock xs = true) :
factory_exclusivity_ok (seqSchedules xs ys) = truetheoremfactory_exclusivity_ok_seqMany_replicate_block
theorem factory_exclusivity_ok_seqMany_replicate_block
(block : List SysCall) (n : Nat)
(hblock : factory_exclusivity_ok block = true)
(hwithin : scheduleWithinWallclock block = true) :
factory_exclusivity_ok (seqManySchedules (List.replicate n block)) = truetheoremfactory_exclusivity_ok_repeated_block_expand
theorem factory_exclusivity_ok_repeated_block_expand
(block : List SysCall) (n : Nat)
(hblock : factory_exclusivity_ok block = true)
(hwithin : scheduleWithinWallclock block = true) :
factory_exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = trueFormalRV.System.Artifacts.CompressedRepeat.FeedbackAfterDecode
FormalRV/System/Artifacts/CompressedRepeat/FeedbackAfterDecode.lean
`feedback_after_decode_ok` under composition (Obligation B).
The self-referential inner `.any` is factored through
`decode_matches_feedback`; the check is shift-invariant, monotone
under `++`, preserved by `seqSchedules` and by n-fold repeat of a
block. Headline: `symbolic_rep_implies_expanded_feedback_after_decode_ok`
— symbolic-repeat acceptance implies the EXPANDED schedule passes the
feedback check, for arbitrary n. No `sorry`, no custom `axiom`.
defdecode_matches_feedback
def decode_matches_feedback (cid b : Nat) (d : SysCall) : Bool
Does the SysCall `d` count as a decoder match for a
`PauliFrameUpdate cid` whose `begin_us` is `b`? Returns
`true` iff `d.kind = DecodeSyndrome cid` and `d.end_us ≤
b`.
This factors the inner-`.any` body of
`feedback_after_decode_ok`, eliminating the
self-reference.
theoremdecode_matches_feedback_shift_same
theorem decode_matches_feedback_shift_same
(cid b dt : Nat) (d : SysCall) :
decode_matches_feedback cid (b + dt) (shiftSysCall dt d)
= decode_matches_feedback cid b dUniform shift on both the candidate decoder `d` and the
feedback begin-time `b` preserves matching.
theoremany_decode_matches_feedback_shift_same
theorem any_decode_matches_feedback_shift_same
(cid b dt : Nat) (xs : List SysCall) :
(shiftSchedule dt xs).any (decode_matches_feedback cid (b + dt))
= xs.any (decode_matches_feedback cid b)The existence of a decoder match under uniform shift is
preserved.
theoremfeedback_after_decode_ok_shiftSchedule
theorem feedback_after_decode_ok_shiftSchedule
(dt : Nat) (xs : List SysCall) :
feedback_after_decode_ok (shiftSchedule dt xs)
= feedback_after_decode_ok xstheoremfeedback_after_decode_ok_shiftSchedule_of_ok
theorem feedback_after_decode_ok_shiftSchedule_of_ok
(dt : Nat) (xs : List SysCall)
(h : feedback_after_decode_ok xs = true) :
feedback_after_decode_ok (shiftSchedule dt xs) = truetheoremList_any_append_left
theorem List_any_append_left
{α : Type _} (xs ys : List α) (p : α → Bool)
(h : xs.any p = true) :
(xs ++ ys).any p = trueA `.any` is monotone under `++`: if the original list
contains a witness, the appended list also contains
one.
theoremList_any_append_right
theorem List_any_append_right
{α : Type _} (xs ys : List α) (p : α → Bool)
(h : ys.any p = true) :
(xs ++ ys).any p = truetheoremfeedback_after_decode_ok_append
theorem feedback_after_decode_ok_append
(xs ys : List SysCall)
(hxs : feedback_after_decode_ok xs = true)
(hys : feedback_after_decode_ok ys = true) :
feedback_after_decode_ok (xs ++ ys) = trueThe main append theorem for feedback-after-decode.
theoremfeedback_after_decode_ok_seqSchedules
theorem feedback_after_decode_ok_seqSchedules
(xs ys : List SysCall)
(hxs : feedback_after_decode_ok xs = true)
(hys : feedback_after_decode_ok ys = true) :
feedback_after_decode_ok (seqSchedules xs ys) = truetheoremfeedback_after_decode_ok_seqMany_replicate
theorem feedback_after_decode_ok_seqMany_replicate
(body : List SysCall) (n : Nat)
(hbody : feedback_after_decode_ok body = true) :
feedback_after_decode_ok
(seqManySchedules (List.replicate n body)) = true`feedback_after_decode_ok` survives sequential
composition of `n` identical bodies via
`seqManySchedules (List.replicate n body)`. By induction
on `n`.
theoremfeedback_after_decode_ok_repeated_atom_expand
theorem feedback_after_decode_ok_repeated_atom_expand
(body : List SysCall) (n : Nat)
(hbody : feedback_after_decode_ok body = true) :
feedback_after_decode_ok
(CompressedSchedule.rep n (CompressedSchedule.atom body)).expand = trueHeadline: `feedback_after_decode_ok` on the EXPANDED form
of `rep n (atom body)`.
theoremsymbolic_rep_ok_implies_body_feedback_after_decode_ok
theorem symbolic_rep_ok_implies_body_feedback_after_decode_ok
(models : SystemModels) (body : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok models body n = true) :
feedback_after_decode_ok body = trueSymbolic-repeat acceptance implies the body passes
`feedback_after_decode_ok` (extracted from the strict
bundle inside `symbolic_rep_strict_ok`).
theoremsymbolic_rep_implies_expanded_feedback_after_decode_ok
theorem symbolic_rep_implies_expanded_feedback_after_decode_ok
(models : SystemModels) (body : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok models body n = true) :
feedback_after_decode_ok
(CompressedSchedule.rep n (CompressedSchedule.atom body)).expand = true*Headline Obligation-B theorem.** The symbolic check
`symbolic_rep_strict_ok` is reps-independent by design (it
checks the body once); this theorem supplies the soundness
leg: acceptance implies the EXPANDED n-fold schedule passes
`feedback_after_decode_ok`, for arbitrary `n`.
FormalRV.System.Artifacts.CompressedRepeat.FreshnessSoundness
FormalRV/System/Artifacts/CompressedRepeat/FreshnessSoundness.lean
Ancilla-freshness soundness under composition (Obligation C, CLOSED).
Part 1 -- state-equivalence machinery: `lifecycleEquivalent` /
`state_equivalent` collapse {Free, Dirty} while keeping Live distinct;
`stateNormalized` is preserved by `setLifecycle` and `runFreshness`;
lookup lemmas go through the Bool-predicate bridge.
Part 2 -- composition: `runFreshness_append`, the success-preserving
one-sided equivalence forms, `ancilla_freshness_ok_seqSchedules`, the
n-fold replicate version, and body extraction from
`symbolic_rep_strict_ok` giving the headline
`symbolic_rep_implies_expanded_block_ancilla_freshness_ok` for
arbitrary n.
The two parts share `match`-generated auxiliary definitions, so they
must live in ONE file (Lean matcher identity is per-module; `rw`
against a `match` pattern from another module does not fire).
No `sorry`, no custom `axiom`.
deflifecycleEquivalent
def lifecycleEquivalent (a b : SiteLifecycle) : Bool
Collapse `Free` and `Dirty` into one class; `Live` is
its own class. Both directions need to map.
defstate_equivalent
def state_equivalent
(s1 s2 : List (Nat × SiteLifecycle)) : PropState equivalence: pointwise lifecycle equivalence at
every site.
theoremstate_equivalent_refl
theorem state_equivalent_refl (s : List (Nat × SiteLifecycle)) :
state_equivalent s stheoremstate_equivalent_symm
theorem state_equivalent_symm
{s1 s2 : List (Nat × SiteLifecycle)}
(h : state_equivalent s1 s2) : state_equivalent s2 s1theoremstate_equivalent_live_iff
theorem state_equivalent_live_iff
{s1 s2 : List (Nat × SiteLifecycle)} (site : Nat)
(h : state_equivalent s1 s2) :
(lifecycleOf s1 site = SiteLifecycle.Live)
↔ (lifecycleOf s2 site = SiteLifecycle.Live)Live status is preserved both ways under state
equivalence.
theoremisLive_eq_under_state_equivalent
theorem isLive_eq_under_state_equivalent
{s1 s2 : List (Nat × SiteLifecycle)} (site : Nat)
(h : state_equivalent s1 s2) :
(match lifecycleOf s1 site with | .Live => true | _ => false)
= (match lifecycleOf s2 site with | .Live => true | _ => false)Live site decision predicate is the same under equivalent
states.
defstateNormalized
def stateNormalized (s : List (Nat × SiteLifecycle)) : Prop
A lifecycle state is *normalized* if no two entries share
the same site identifier. `runFreshness` starting from
`[]` is expected to preserve this invariant because
every `setLifecycle` first filters out all entries with
the target site.
theoremstateNormalized_nil
theorem stateNormalized_nil :
stateNormalized ([] : List (Nat × SiteLifecycle))theoremlifecycleOf_nil
theorem lifecycleOf_nil (site : Nat) :
lifecycleOf ([] : List (Nat × SiteLifecycle)) site = SiteLifecycle.FreetheoremnoDanglingLive_implies_state_equivalent_empty
theorem noDanglingLive_implies_state_equivalent_empty
(s : List (Nat × SiteLifecycle))
(h : noDanglingLive s = true) :
state_equivalent s []defdropSite
def dropSite (s : List (Nat × SiteLifecycle)) (site : Nat) : List (Nat × SiteLifecycle)
`s.filter` with an explicit Bool predicate that drops
every entry whose first coord equals `site`.
defsetLifecycleBool
def setLifecycleBool (s : List (Nat × SiteLifecycle)) (site : Nat)
(lc : SiteLifecycle) : List (Nat × SiteLifecycle)Bool-predicate variant of `setLifecycle`.
theoremsetLifecycle_eq_setLifecycleBool
theorem setLifecycle_eq_setLifecycleBool
(s : List (Nat × SiteLifecycle)) (site : Nat) (lc : SiteLifecycle) :
setLifecycle s site lc = setLifecycleBool s site lc`setLifecycle` and `setLifecycleBool` produce the same
list because `¬ decide (p.1 = site)` (as a Bool via
coercion) equals `!decide (p.1 = site)`.
theoremmem_dropSite_iff
theorem mem_dropSite_iff
{s : List (Nat × SiteLifecycle)} {site : Nat}
{p : Nat × SiteLifecycle} :
p ∈ dropSite s site ↔ p ∈ s ∧ p.1 ≠ sitetheoremnot_mem_dropSite_same
theorem not_mem_dropSite_same
{s : List (Nat × SiteLifecycle)} {site : Nat} :
∀ p ∈ dropSite s site, p.1 ≠ sitetheoremfind?_dropSite_eq_none
private theorem find?_dropSite_eq_none
(s : List (Nat × SiteLifecycle)) (site : Nat) :
(dropSite s site).find? (fun p => decide (p.1 = site)) = nonetheoremlifecycleOf_setLifecycleBool_same
theorem lifecycleOf_setLifecycleBool_same
(s : List (Nat × SiteLifecycle)) (site : Nat) (lc : SiteLifecycle) :
lifecycleOf (setLifecycleBool s site lc) site = lctheoremfind?_dropSite_other
private theorem find?_dropSite_other
(s : List (Nat × SiteLifecycle)) (site site' : Nat) (hne : site' ≠ site) :
(dropSite s site).find? (fun p => decide (p.1 = site'))
= s.find? (fun p => decide (p.1 = site'))theoremlifecycleOf_setLifecycleBool_other
theorem lifecycleOf_setLifecycleBool_other
(s : List (Nat × SiteLifecycle)) (site site' : Nat) (lc : SiteLifecycle)
(hne : site' ≠ site) :
lifecycleOf (setLifecycleBool s site lc) site' = lifecycleOf s site'theoremlifecycleOf_setLifecycle_same
theorem lifecycleOf_setLifecycle_same
(s : List (Nat × SiteLifecycle)) (site : Nat) (lc : SiteLifecycle) :
lifecycleOf (setLifecycle s site lc) site = lctheoremlifecycleOf_setLifecycle_other
theorem lifecycleOf_setLifecycle_other
(s : List (Nat × SiteLifecycle)) (site site' : Nat) (lc : SiteLifecycle)
(hne : site' ≠ site) :
lifecycleOf (setLifecycle s site lc) site' = lifecycleOf s site'theoremstateNormalized_dropSite
theorem stateNormalized_dropSite
{s : List (Nat × SiteLifecycle)} (h : stateNormalized s)
(site : Nat) :
stateNormalized (dropSite s site)theoremstateNormalized_setLifecycleBool
theorem stateNormalized_setLifecycleBool
{s : List (Nat × SiteLifecycle)} (h : stateNormalized s)
(site : Nat) (lc : SiteLifecycle) :
stateNormalized (setLifecycleBool s site lc)theoremstateNormalized_setLifecycle
theorem stateNormalized_setLifecycle
{s : List (Nat × SiteLifecycle)} (h : stateNormalized s)
(site : Nat) (lc : SiteLifecycle) :
stateNormalized (setLifecycle s site lc)theoremfreshnessStep_result_form
theorem freshnessStep_result_form
(model : AncillaModel) (state : List (Nat × SiteLifecycle))
(sc : SysCall) (state' : List (Nat × SiteLifecycle))
(hStep : freshnessStep model state sc = some state') :
state' = state ∨ ∃ site lc, state' = setLifecycle state site lcA successful `freshnessStep` either leaves the state
unchanged or applies a single `setLifecycle`. This
factors away the SysCallKind enumeration so downstream
proofs (preservation, equivalence) reduce to two cases.
theoremfreshnessStep_preserves_stateNormalized
theorem freshnessStep_preserves_stateNormalized
(model : AncillaModel) (state : List (Nat × SiteLifecycle))
(sc : SysCall) (state' : List (Nat × SiteLifecycle))
(hNorm : stateNormalized state)
(hStep : freshnessStep model state sc = some state') :
stateNormalized state'theoremrunFreshness_preserves_stateNormalized
theorem runFreshness_preserves_stateNormalized
(model : AncillaModel) (sched : List SysCall)
(state : List (Nat × SiteLifecycle))
(state' : List (Nat × SiteLifecycle))
(hNorm : stateNormalized state)
(hRun : runFreshness model state sched = some state') :
stateNormalized state'theoremstate_equivalent_set_same
theorem state_equivalent_set_same
{s1 s2 : List (Nat × SiteLifecycle)}
(h : state_equivalent s1 s2)
(site : Nat) (lc : SiteLifecycle) :
state_equivalent
(setLifecycle s1 site lc) (setLifecycle s2 site lc)theoremfreshnessStep_state_equivalent
theorem freshnessStep_state_equivalent
(model : AncillaModel) (sc : SysCall)
(s1 s2 s1' s2' : List (Nat × SiteLifecycle))
(hEq : state_equivalent s1 s2)
(h1 : freshnessStep model s1 sc = some s1')
(h2 : freshnessStep model s2 sc = some s2') :
state_equivalent s1' s2'theoremrunFreshness_state_equivalent
theorem runFreshness_state_equivalent
(model : AncillaModel) (sched : List SysCall)
(s1 s2 s1' s2' : List (Nat × SiteLifecycle))
(hEq : state_equivalent s1 s2)
(h1 : runFreshness model s1 sched = some s1')
(h2 : runFreshness model s2 sched = some s2') :
state_equivalent s1' s2'theoremlifecycleOf_eq_of_mem_normalized
theorem lifecycleOf_eq_of_mem_normalized
{s : List (Nat × SiteLifecycle)} (hnorm : stateNormalized s)
{p : Nat × SiteLifecycle} (hp : p ∈ s) :
lifecycleOf s p.1 = p.2theoremstate_equivalent_empty_implies_noDanglingLive
theorem state_equivalent_empty_implies_noDanglingLive
(s : List (Nat × SiteLifecycle))
(h : state_equivalent s []) (hnorm : stateNormalized s) :
noDanglingLive s = truetheoremstate_equivalent_trans
theorem state_equivalent_trans
{s1 s2 s3 : List (Nat × SiteLifecycle)}
(h12 : state_equivalent s1 s2) (h23 : state_equivalent s2 s3) :
state_equivalent s1 s3theoremrunFreshness_append
theorem runFreshness_append
(model : AncillaModel) (state : List (Nat × SiteLifecycle))
(xs ys : List SysCall) :
runFreshness model state (xs ++ ys)
= (match runFreshness model state xs with
| none => none
| some state' => runFreshness model state' ys)theoremfreshnessStep_state_equivalent_some_form
theorem freshnessStep_state_equivalent_some_form
(model : AncillaModel) (sc : SysCall)
(s1 s2 t2 : List (Nat × SiteLifecycle))
(hEq : state_equivalent s1 s2)
(h2 : freshnessStep model s2 sc = some t2) :
∃ t1, freshnessStep model s1 sc = some t1 ∧ state_equivalent t1 t2theoremrunFreshness_state_equivalent_some_form
theorem runFreshness_state_equivalent_some_form
(model : AncillaModel) (sched : List SysCall)
(s1 s2 s2' : List (Nat × SiteLifecycle))
(hEq : state_equivalent s1 s2)
(h2 : runFreshness model s2 sched = some s2') :
∃ s1', runFreshness model s1 sched = some s1' ∧ state_equivalent s1' s2'theoremancilla_freshness_ok_seqSchedules
theorem ancilla_freshness_ok_seqSchedules
(model : AncillaModel) (xs ys : List SysCall)
(hxs : ancilla_freshness_ok model xs = true)
(hys : ancilla_freshness_ok model ys = true) :
ancilla_freshness_ok model (seqSchedules xs ys) = truetheoremancilla_freshness_ok_seqMany_replicate_block
theorem ancilla_freshness_ok_seqMany_replicate_block
(model : AncillaModel) (block : List SysCall) (n : Nat)
(hblock : ancilla_freshness_ok model block = true) :
ancilla_freshness_ok model
(seqManySchedules (List.replicate n block)) = truetheoremancilla_freshness_ok_repeated_block_expand
theorem ancilla_freshness_ok_repeated_block_expand
(model : AncillaModel) (block : List SysCall) (n : Nat)
(hblock : ancilla_freshness_ok model block = true) :
ancilla_freshness_ok model
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_ok_implies_body_ancilla_freshness_ok
theorem symbolic_rep_ok_implies_body_ancilla_freshness_ok
(models : SystemModels) (body : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok models body n = true) :
ancilla_freshness_ok models.ancillaModel body = truetheoremsymbolic_rep_implies_expanded_block_ancilla_freshness_ok
theorem symbolic_rep_implies_expanded_block_ancilla_freshness_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
ancilla_freshness_ok models.ancillaModel
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = trueFormalRV.System.Artifacts.CompressedRepeat.InvariantChains
FormalRV/System/Artifacts/CompressedRepeat/InvariantChains.lean
seqSchedules / replicate / expanded-repeat chains for the remaining
strict-bundle conjuncts: `capacity_in_arch_ok`,
`feedback_latency_ok`, `decoder_react_ok` (per-syscall, immediate
from the ShiftInvariance lemmas plus `List.all_append`);
`window_throughput_ok` (vacuous on magic-free blocks, with the
magic-count bookkeeping under append/shift/replicate); and the
sampled-time `capacity_per_cycle_ok` (via the CapacitySeq
`activeSitesAt` helpers). No `sorry`, no custom `axiom`.
theoremcapacity_in_arch_ok_seqSchedules
theorem capacity_in_arch_ok_seqSchedules
(arch : ZonedArch) (xs ys : List SysCall)
(hxs : capacity_in_arch_ok arch xs = true)
(hys : capacity_in_arch_ok arch ys = true) :
capacity_in_arch_ok arch (seqSchedules xs ys) = truetheoremcapacity_in_arch_ok_seqMany_replicate_block
theorem capacity_in_arch_ok_seqMany_replicate_block
(arch : ZonedArch) (block : List SysCall) (n : Nat)
(hblock : capacity_in_arch_ok arch block = true) :
capacity_in_arch_ok arch
(seqManySchedules (List.replicate n block)) = truetheoremcapacity_in_arch_ok_repeated_block_expand
theorem capacity_in_arch_ok_repeated_block_expand
(arch : ZonedArch) (block : List SysCall) (n : Nat)
(hblock : capacity_in_arch_ok arch block = true) :
capacity_in_arch_ok arch
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremfeedback_latency_ok_seqSchedules
theorem feedback_latency_ok_seqSchedules
(t_cycle_us : Nat) (xs ys : List SysCall)
(hxs : feedback_latency_ok t_cycle_us xs = true)
(hys : feedback_latency_ok t_cycle_us ys = true) :
feedback_latency_ok t_cycle_us (seqSchedules xs ys) = truetheoremfeedback_latency_ok_seqMany_replicate_block
theorem feedback_latency_ok_seqMany_replicate_block
(t_cycle_us : Nat) (block : List SysCall) (n : Nat)
(hblock : feedback_latency_ok t_cycle_us block = true) :
feedback_latency_ok t_cycle_us
(seqManySchedules (List.replicate n block)) = truetheoremfeedback_latency_ok_repeated_block_expand
theorem feedback_latency_ok_repeated_block_expand
(t_cycle_us : Nat) (block : List SysCall) (n : Nat)
(hblock : feedback_latency_ok t_cycle_us block = true) :
feedback_latency_ok t_cycle_us
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremdecoder_react_ok_seqSchedules
theorem decoder_react_ok_seqSchedules
(t_react_us : Nat) (xs ys : List SysCall)
(hxs : decoder_react_ok t_react_us xs = true)
(hys : decoder_react_ok t_react_us ys = true) :
decoder_react_ok t_react_us (seqSchedules xs ys) = truetheoremdecoder_react_ok_seqMany_replicate_block
theorem decoder_react_ok_seqMany_replicate_block
(t_react_us : Nat) (block : List SysCall) (n : Nat)
(hblock : decoder_react_ok t_react_us block = true) :
decoder_react_ok t_react_us
(seqManySchedules (List.replicate n block)) = truetheoremdecoder_react_ok_repeated_block_expand
theorem decoder_react_ok_repeated_block_expand
(t_react_us : Nat) (block : List SysCall) (n : Nat)
(hblock : decoder_react_ok t_react_us block = true) :
decoder_react_ok t_react_us
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremmagic_count_append
theorem magic_count_append (xs ys : List SysCall) :
((xs ++ ys).filter (fun sc => kindIsMagicReq sc.kind)).length
= (xs.filter (fun sc => kindIsMagicReq sc.kind)).length
+ (ys.filter (fun sc => kindIsMagicReq sc.kind)).lengththeoremmagic_count_seqMany_replicate
theorem magic_count_seqMany_replicate
(block : List SysCall) (n : Nat)
(h : (block.filter (fun sc => kindIsMagicReq sc.kind)).length = 0) :
((seqManySchedules (List.replicate n block)).filter
(fun sc => kindIsMagicReq sc.kind)).length = 0theoremmagic_count_repeated_block_expand
theorem magic_count_repeated_block_expand
(block : List SysCall) (n : Nat)
(h : (block.filter (fun sc => kindIsMagicReq sc.kind)).length = 0) :
(((CompressedSchedule.rep n (CompressedSchedule.atom block)).expand).filter
(fun sc => kindIsMagicReq sc.kind)).length = 0theoremwindow_throughput_ok_of_no_magic
theorem window_throughput_ok_of_no_magic
(sched : List SysCall) (window_us max_per_window : Nat)
(h : (sched.filter (fun sc => kindIsMagicReq sc.kind)).length = 0) :
window_throughput_ok sched window_us max_per_window = truedefcap_per_cycle_check_at
private def cap_per_cycle_check_at
(arch : ZonedArch) (L : List SysCall) (t : Nat) : Booltheoremcapacity_per_cycle_ok_eq
private theorem capacity_per_cycle_ok_eq
(arch : ZonedArch) (L : List SysCall) :
capacity_per_cycle_ok arch L
= (scheduleEventTimes L).all (cap_per_cycle_check_at arch L)theoremcap_per_cycle_check_at_shiftSchedule
private theorem cap_per_cycle_check_at_shiftSchedule
(arch : ZonedArch) (xs : List SysCall) (t dt : Nat) :
cap_per_cycle_check_at arch (shiftSchedule dt xs) (t + dt)
= cap_per_cycle_check_at arch xs ttheoremcapacity_per_cycle_ok_shiftSchedule_eq
theorem capacity_per_cycle_ok_shiftSchedule_eq
(arch : ZonedArch) (dt : Nat) (xs : List SysCall) :
capacity_per_cycle_ok arch (shiftSchedule dt xs)
= capacity_per_cycle_ok arch xstheoremcapacity_per_cycle_ok_seqSchedules
theorem capacity_per_cycle_ok_seqSchedules
(arch : ZonedArch) (xs ys : List SysCall)
(hxs : capacity_per_cycle_ok arch xs = true)
(hys : capacity_per_cycle_ok arch ys = true)
(hwithin : scheduleWithinWallclock xs = true) :
capacity_per_cycle_ok arch (seqSchedules xs ys) = truetheoremcapacity_per_cycle_ok_seqMany_replicate_block
theorem capacity_per_cycle_ok_seqMany_replicate_block
(arch : ZonedArch) (block : List SysCall) (n : Nat)
(hblock : capacity_per_cycle_ok arch block = true)
(hwithin : scheduleWithinWallclock block = true) :
capacity_per_cycle_ok arch
(seqManySchedules (List.replicate n block)) = truetheoremcapacity_per_cycle_ok_repeated_block_expand
theorem capacity_per_cycle_ok_repeated_block_expand
(arch : ZonedArch) (block : List SysCall) (n : Nat)
(hblock : capacity_per_cycle_ok arch block = true)
(hwithin : scheduleWithinWallclock block = true) :
capacity_per_cycle_ok arch
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = trueFormalRV.System.Artifacts.CompressedRepeat.ResourceCorrectness
FormalRV/System/Artifacts/CompressedRepeat/ResourceCorrectness.lean
FormalRV.System.Artifacts.CompressedRepeat.ResourceCorrectness —
*the symbolic resource evaluator is CORRECT against the canonical
counters on the expansion**, for EVERY CompressedSchedule (atoms, seq,
par, rep — arbitrarily nested):
cs.resource = resourceOfSysCalls cs.expand
This closes the audited gap "no parametric count=expand theorem": the
10⁹-op headline ("Lean re-derives the claimed numbers symbolically")
now rests on a proof that the symbolic numbers equal THE canonical
`Resource/SysCallCount` walks over the materialized schedule — for any
n, any nesting — not on an n=3 spot check.
theoremresourceOfSysCalls_nil
theorem resourceOfSysCalls_nil :
resourceOfSysCalls [] = CompressedResourceSummary.zerotheoremresourceOfSysCalls_seqSchedules
theorem resourceOfSysCalls_seqSchedules (xs ys : List SysCall) :
resourceOfSysCalls (seqSchedules xs ys)
= seqCombine (resourceOfSysCalls xs) (resourceOfSysCalls ys)theoremresourceOfSysCalls_parSchedules
theorem resourceOfSysCalls_parSchedules (xs ys : List SysCall) :
resourceOfSysCalls (parSchedules xs ys)
= parCombine (resourceOfSysCalls xs) (resourceOfSysCalls ys)theoremresourceOfSysCalls_seqMany
theorem resourceOfSysCalls_seqMany (ls : List (List SysCall)) :
resourceOfSysCalls (seqManySchedules ls)
= (ls.map resourceOfSysCalls).foldr seqCombine zerotheoremresourceOfSysCalls_parMany
theorem resourceOfSysCalls_parMany (ls : List (List SysCall)) :
resourceOfSysCalls (parManySchedules ls)
= (ls.map resourceOfSysCalls).foldr parCombine zerotheoremscale_succ
theorem scale_succ (n : Nat) (r : CompressedResourceSummary) :
scale (n + 1) r = seqCombine r (scale n r)`scale` is iterated `seqCombine` (field-wise `(n+1)·x = x + n·x`).
theoremfoldr_seqCombine_replicate
theorem foldr_seqCombine_replicate (n : Nat) (r : CompressedResourceSummary) :
(List.replicate n r).foldr seqCombine zero = scale n rtheoremresource_eq_expand
theorem resource_eq_expand :
(cs : CompressedSchedule) →
cs.resource = resourceOfSysCalls cs.expand
| .atom xs =>*`CompressedSchedule.resource` = the canonical counters on the
expansion** — for every schedule shape, every nesting, every `n`.
theoremresource_wallclock_eq
theorem resource_wallclock_eq (cs : CompressedSchedule) :
cs.resource.wallclock_us = wallclockUs cs.expandtheoremresource_syscall_count_eq
theorem resource_syscall_count_eq (cs : CompressedSchedule) :
cs.resource.syscall_count = opCountS cs.expandtheoremresource_gate2q_eq
theorem resource_gate2q_eq (cs : CompressedSchedule) :
cs.resource.gate2q_count = countGate2q cs.expandtheoremresource_magic_req_eq
theorem resource_magic_req_eq (cs : CompressedSchedule) :
cs.resource.magic_req_count = countMagicReq cs.expandFormalRV.System.Artifacts.CompressedRepeat.ShiftInvariance
FormalRV/System/Artifacts/CompressedRepeat/ShiftInvariance.lean
Shift/append invariance core for SysCall schedules.
§1–§6: `shiftSysCall` / `shiftSchedule` preserve `kind`, duration,
`syscall_acts_on`, `syscall_factory_claims`; the per-call
strict-bundle conjuncts (`capacity_in_arch_ok`,
`feedback_latency_ok`, `decoder_react_ok`, `ancilla_freshness_ok`)
and magic counts are invariant under uniform time shift.
§9.a–d: the sequential-composition window basics. A block is
`scheduleWithinWallclock` when every SysCall has positive duration
and ends by the block's wallclock (§9.a); the shifted second block
of a `seqSchedules` then begins at or after the first block's
wallclock (`shifted_begin_ge_offset`, §9.b); with the
interval-overlap lemmas (§9.c) this yields `cross_pair_no_overlap`
(§9.d) — no SysCall of the first block overlaps any SysCall of the
shifted second block. This is the geometric fact behind every
pairwise/capacity repeat chain in the CompressedRepeat split.
Finally, `rep_atom_expand_eq : (rep n (atom b)).expand =
seqManySchedules (List.replicate n b)` reduces compressed repeats
to sequential composition. Foundation for the rest of the
CompressedRepeat split. No `sorry`, no custom `axiom`.
theoremshiftSysCall_duration
theorem shiftSysCall_duration (dt : Nat) (sc : SysCall) :
(shiftSysCall dt sc).end_us - (shiftSysCall dt sc).begin_us
= sc.end_us - sc.begin_ustheoremsyscall_acts_on_shiftSysCall
theorem syscall_acts_on_shiftSysCall (dt : Nat) (sc : SysCall) :
syscall_acts_on (shiftSysCall dt sc) = syscall_acts_on sctheoremsyscall_factory_claims_shiftSysCall
theorem syscall_factory_claims_shiftSysCall (dt : Nat) (sc : SysCall) :
syscall_factory_claims (shiftSysCall dt sc) = syscall_factory_claims sctheoremcapacity_in_arch_ok_shiftSchedule
theorem capacity_in_arch_ok_shiftSchedule
(arch : ZonedArch) (dt : Nat) (xs : List SysCall) :
capacity_in_arch_ok arch (shiftSchedule dt xs)
= capacity_in_arch_ok arch xstheoremcapacity_in_arch_ok_shiftSchedule_of_ok
theorem capacity_in_arch_ok_shiftSchedule_of_ok
(arch : ZonedArch) (dt : Nat) (xs : List SysCall)
(h : capacity_in_arch_ok arch xs = true) :
capacity_in_arch_ok arch (shiftSchedule dt xs) = truetheoremfeedback_latency_ok_shiftSchedule
theorem feedback_latency_ok_shiftSchedule
(t_cycle_us dt : Nat) (xs : List SysCall) :
feedback_latency_ok t_cycle_us (shiftSchedule dt xs)
= feedback_latency_ok t_cycle_us xstheoremfeedback_latency_ok_shiftSchedule_of_ok
theorem feedback_latency_ok_shiftSchedule_of_ok
(t_cycle_us dt : Nat) (xs : List SysCall)
(h : feedback_latency_ok t_cycle_us xs = true) :
feedback_latency_ok t_cycle_us (shiftSchedule dt xs) = truetheoremdecoder_react_ok_shiftSchedule
theorem decoder_react_ok_shiftSchedule
(t_react_us dt : Nat) (xs : List SysCall) :
decoder_react_ok t_react_us (shiftSchedule dt xs)
= decoder_react_ok t_react_us xstheoremdecoder_react_ok_shiftSchedule_of_ok
theorem decoder_react_ok_shiftSchedule_of_ok
(t_react_us dt : Nat) (xs : List SysCall)
(h : decoder_react_ok t_react_us xs = true) :
decoder_react_ok t_react_us (shiftSchedule dt xs) = truetheoremfreshnessStep_shiftSysCall
theorem freshnessStep_shiftSysCall
(model : AncillaModel) (state : List (Nat × SiteLifecycle))
(dt : Nat) (sc : SysCall) :
freshnessStep model state (shiftSysCall dt sc)
= freshnessStep model state sctheoremrunFreshness_shiftSchedule
theorem runFreshness_shiftSchedule
(model : AncillaModel) (state : List (Nat × SiteLifecycle))
(dt : Nat) (xs : List SysCall) :
runFreshness model state (shiftSchedule dt xs)
= runFreshness model state xstheoremancilla_freshness_ok_shiftSchedule
theorem ancilla_freshness_ok_shiftSchedule
(model : AncillaModel) (dt : Nat) (xs : List SysCall) :
ancilla_freshness_ok model (shiftSchedule dt xs)
= ancilla_freshness_ok model xstheoremancilla_freshness_ok_shiftSchedule_of_ok
theorem ancilla_freshness_ok_shiftSchedule_of_ok
(model : AncillaModel) (dt : Nat) (xs : List SysCall)
(h : ancilla_freshness_ok model xs = true) :
ancilla_freshness_ok model (shiftSchedule dt xs) = truetheoremkindIsMagicReq_shiftSysCall
theorem kindIsMagicReq_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsMagicReq (shiftSysCall dt sc).kind = kindIsMagicReq sc.kindtheoremkindIsGate2q_shiftSysCall
theorem kindIsGate2q_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsGate2q (shiftSysCall dt sc).kind = kindIsGate2q sc.kindtheoremkindIsMeasure_shiftSysCall
theorem kindIsMeasure_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsMeasure (shiftSysCall dt sc).kind = kindIsMeasure sc.kindtheoremkindIsDecode_shiftSysCall
theorem kindIsDecode_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsDecode (shiftSysCall dt sc).kind = kindIsDecode sc.kindtheoremkindIsFeedback_shiftSysCall
theorem kindIsFeedback_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsFeedback (shiftSysCall dt sc).kind = kindIsFeedback sc.kindtheoremkindIsFreshAnc_shiftSysCall
theorem kindIsFreshAnc_shiftSysCall (dt : Nat) (sc : SysCall) :
kindIsFreshAnc (shiftSysCall dt sc).kind = kindIsFreshAnc sc.kindtheoremmagic_count_shiftSchedule
theorem magic_count_shiftSchedule (dt : Nat) (xs : List SysCall) :
((shiftSchedule dt xs).filter (fun sc => kindIsMagicReq sc.kind)).length
= (xs.filter (fun sc => kindIsMagicReq sc.kind)).lengththeoremno_magic_shiftSchedule
theorem no_magic_shiftSchedule
(dt : Nat) (xs : List SysCall)
(h : (xs.filter fun sc => kindIsMagicReq sc.kind).length = 0) :
((shiftSchedule dt xs).filter fun sc => kindIsMagicReq sc.kind).length = 0defscheduleWithinWallclock
def scheduleWithinWallclock (xs : List SysCall) : Bool
A schedule is "within-wallclock" if every SysCall has
`begin_us < end_us` and `end_us ≤ scheduleWallclockUs xs`.
The strict inequality `begin_us < end_us` excludes
zero-duration SysCalls; all compiler-emitted schedules
satisfy this (durations are positive integers).
theoremscheduleWithinWallclock_end_le
theorem scheduleWithinWallclock_end_le
(xs : List SysCall) (sc : SysCall)
(hmem : sc ∈ xs) (h : scheduleWithinWallclock xs = true) :
sc.end_us ≤ scheduleWallclockUs xsMembership consequence: any SysCall in a within-wallclock
schedule has `end_us ≤ scheduleWallclockUs xs`.
theoremscheduleWithinWallclock_begin_lt_end
theorem scheduleWithinWallclock_begin_lt_end
(xs : List SysCall) (sc : SysCall)
(hmem : sc ∈ xs) (h : scheduleWithinWallclock xs = true) :
sc.begin_us < sc.end_ustheoremshifted_begin_ge_offset
theorem shifted_begin_ge_offset
(dt : Nat) (ys : List SysCall) (sc : SysCall)
(hmem : sc ∈ shiftSchedule dt ys) :
dt ≤ sc.begin_ustheoremintervals_overlap_shift_same
theorem intervals_overlap_shift_same
(a_lo a_hi b_lo b_hi dt : Nat) :
intervals_overlap (a_lo + dt) (a_hi + dt) (b_lo + dt) (b_hi + dt)
= intervals_overlap a_lo a_hi b_lo b_hi`intervals_overlap` is invariant under uniform shift.
theoremintervals_overlap_disjoint_when_le
theorem intervals_overlap_disjoint_when_le
(a_lo a_hi b_lo b_hi : Nat) (h : a_hi ≤ b_lo) :
intervals_overlap a_lo a_hi b_lo b_hi = falseIf `a_hi ≤ b_lo`, the half-open intervals
`[a_lo, a_hi)` and `[b_lo, b_hi)` do not overlap.
theoremcross_pair_no_overlap
theorem cross_pair_no_overlap
(xs ys : List SysCall)
(sc₁ sc₂ : SysCall)
(h₁ : sc₁ ∈ xs)
(h₂ : sc₂ ∈ shiftSchedule (scheduleWallclockUs xs) ys)
(hwithin : scheduleWithinWallclock xs = true) :
intervals_overlap sc₁.begin_us sc₁.end_us sc₂.begin_us sc₂.end_us = falsetheoremrep_atom_expand_eq
theorem rep_atom_expand_eq (body : List SysCall) (n : Nat) :
(CompressedSchedule.rep n (CompressedSchedule.atom body)).expand
= seqManySchedules (List.replicate n body)Reduction lemma: `(rep n (atom body)).expand` equals
`seqManySchedules (List.replicate n body)`. The
`CompressedSchedule.expand` recursor uses well-founded
recursion, so we go via `simp` rather than `rfl`.
FormalRV.System.Artifacts.CompressedRepeat.SymbolicRepeatSoundness
FormalRV/System/Artifacts/CompressedRepeat/SymbolicRepeatSoundness.lean
Parametric symbolic-repeat soundness (Obligations A/B/C).
`symbolic_rep_strict_ok` is reps-independent by design: it checks
the body once, never `n` copies. This file proves that design
sound: acceptance implies the EXPANDED n-fold schedule passes the
strict bundle, for arbitrary `n`. Contents: per-conjunct body
extraction from `symbolic_rep_strict_ok`, expanded-form headlines
for every strict-bundle conjunct, the combined theorem
`symbolic_rep_implies_expanded_block_strict_ok`, and the
self-contained certificate `symbolic_rep_strict_ok_within`
(strict bundle + `scheduleWithinWallclock`) with its soundness
theorem and the paper-facing alias
`hardware_generic_repeated_block_strict_soundness`. Hardware-generic:
`CompressedSchedule.atom` is a leaf schedule block of any backend,
not a hardware-atomic operation. No `sorry`, no custom `axiom`.
theoremsymbolic_rep_ok_implies_body_exclusivity_ok
theorem symbolic_rep_ok_implies_body_exclusivity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
exclusivity_ok block = truetheoremsymbolic_rep_ok_implies_body_factory_exclusivity_ok
theorem symbolic_rep_ok_implies_body_factory_exclusivity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
factory_exclusivity_ok block = truetheoremsymbolic_rep_ok_implies_body_operation_capacity_ok
theorem symbolic_rep_ok_implies_body_operation_capacity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
operation_capacity_ok models.opCap block = truetheoremsymbolic_rep_ok_implies_body_slot_capacity_ok
theorem symbolic_rep_ok_implies_body_slot_capacity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
slot_capacity_ok models.slotCap block = truetheoremsymbolic_rep_implies_expanded_block_exclusivity_ok
theorem symbolic_rep_implies_expanded_block_exclusivity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_factory_exclusivity_ok
theorem symbolic_rep_implies_expanded_block_factory_exclusivity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
factory_exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_operation_capacity_ok
theorem symbolic_rep_implies_expanded_block_operation_capacity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
operation_capacity_ok models.opCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_slot_capacity_ok
theorem symbolic_rep_implies_expanded_block_slot_capacity_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
slot_capacity_ok models.slotCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_combined_strict_ok
theorem symbolic_rep_implies_expanded_block_combined_strict_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = true
∧ factory_exclusivity_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = true
∧ operation_capacity_ok models.opCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = true
∧ slot_capacity_ok models.slotCap
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_ok_implies_body_capacity_in_arch_ok
theorem symbolic_rep_ok_implies_body_capacity_in_arch_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
capacity_in_arch_ok models.arch block = truetheoremsymbolic_rep_ok_implies_body_capacity_per_cycle_ok
theorem symbolic_rep_ok_implies_body_capacity_per_cycle_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
capacity_per_cycle_ok models.arch block = truetheoremsymbolic_rep_ok_implies_body_feedback_latency_ok
theorem symbolic_rep_ok_implies_body_feedback_latency_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
feedback_latency_ok models.arch.t_cycle_us block = truetheoremsymbolic_rep_ok_implies_body_decoder_react_ok
theorem symbolic_rep_ok_implies_body_decoder_react_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
decoder_react_ok models.t_react_us block = truetheoremsymbolic_rep_ok_implies_body_no_magic
theorem symbolic_rep_ok_implies_body_no_magic
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
(block.filter (fun sc => kindIsMagicReq sc.kind)).length = 0theoremsymbolic_rep_implies_expanded_block_capacity_in_arch_ok
theorem symbolic_rep_implies_expanded_block_capacity_in_arch_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
capacity_in_arch_ok models.arch
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_capacity_per_cycle_ok
theorem symbolic_rep_implies_expanded_block_capacity_per_cycle_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
capacity_per_cycle_ok models.arch
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_feedback_latency_ok
theorem symbolic_rep_implies_expanded_block_feedback_latency_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
feedback_latency_ok models.arch.t_cycle_us
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_decoder_react_ok
theorem symbolic_rep_implies_expanded_block_decoder_react_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
decoder_react_ok models.t_react_us
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand = truetheoremsymbolic_rep_implies_expanded_block_window_throughput_ok
theorem symbolic_rep_implies_expanded_block_window_throughput_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true) :
window_throughput_ok
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand
models.window_us models.max_per_window = truetheoremsymbolic_rep_implies_expanded_block_strict_ok
theorem symbolic_rep_implies_expanded_block_strict_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hSym : symbolic_rep_strict_ok models block n = true)
(hwithin : scheduleWithinWallclock block = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand
models.t_react_us
models.window_usdefsymbolic_rep_strict_ok_within
def symbolic_rep_strict_ok_within
(models : SystemModels) (block : List SysCall) (n : Nat) : Booltheoremsymbolic_rep_strict_ok_within_implies_symbolic_rep_strict_ok
theorem symbolic_rep_strict_ok_within_implies_symbolic_rep_strict_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hCert : symbolic_rep_strict_ok_within models block n = true) :
symbolic_rep_strict_ok models block n = truetheoremsymbolic_rep_strict_ok_within_implies_scheduleWithinWallclock
theorem symbolic_rep_strict_ok_within_implies_scheduleWithinWallclock
(models : SystemModels) (block : List SysCall) (n : Nat)
(hCert : symbolic_rep_strict_ok_within models block n = true) :
scheduleWithinWallclock block = truetheoremsymbolic_rep_strict_ok_within_implies_expanded_block_strict_ok
theorem symbolic_rep_strict_ok_within_implies_expanded_block_strict_ok
(models : SystemModels) (block : List SysCall) (n : Nat)
(hCert : symbolic_rep_strict_ok_within models block n = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand
models.t_react_us
models.window_us
models.max_per_window = truetheoremhardware_generic_repeated_block_strict_soundness
theorem hardware_generic_repeated_block_strict_soundness
(models : SystemModels) (block : List SysCall) (n : Nat)
(hCert : symbolic_rep_strict_ok_within models block n = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch
models.opCap
models.slotCap
models.ancillaModel
(CompressedSchedule.rep n (CompressedSchedule.atom block)).expand
models.t_react_us
models.window_us
models.max_per_window = truePaper-facing alias for §13.b.14.
The certificate check `symbolic_rep_strict_ok_within` is
reps-independent by design: it checks the block once;
this theorem is the soundness of that design for the
expanded n-fold schedule.
`CompressedSchedule.atom` is the implementation-level
constructor for a compressed leaf schedule block. The
theorem is hardware-generic: the block may represent a PPM
block, lattice-surgery gadget, neutral-atom routing
schedule, superconducting routing block, ion-trap shuttling
block, factory/decoder service block, or any other verified
system-level schedule block.
FormalRV.System.Artifacts.CompressedRepeatSoundness
FormalRV/System/Artifacts/CompressedRepeatSoundness.lean
FormalRV.System.CompressedRepeatSoundness — umbrella module.
Re-exports the CompressedRepeat split (shift-invariance core,
feedback-after-decode, freshness state-equivalence + repeat,
exclusivity / capacity / remaining-conjunct seq chains, the
parametric symbolic-repeat soundness headlines, the recursive
compressed-schedule certificate, and the concrete adder
regressions). All declarations keep their original fully-qualified
names in namespace `FormalRV.System.CompressedRepeatSoundness`, so
existing `import` / `open` sites are unaffected.
Status: the parametric symbolic-repeat soundness program is CLOSED
(former Obligations A, B, C all proven). General entry point:
`compressed_schedule_strict_soundness` — certificate acceptance
implies the strict invariant bundle on the expansion. No `sorry`,
no custom `axiom`.
(no documented top-level declarations)
FormalRV.System.Artifacts.CompressedSchedule
FormalRV/System/Artifacts/CompressedSchedule.lean
FormalRV.System.Artifacts.CompressedSchedule — hierarchical
schedules (`atom` / `seq` / `par` / `rep`) for scalable
certification of full FT Shor schedules without materializing
the entire `List SysCall`. (Namespace
`FormalRV.System.LayeredArtifactInterface`, shared with the
sibling `LayeredArtifactCore.lean`.)
`CompressedSchedule.expand` — reference expansion semantics
via `seqManySchedules` / `parManySchedules`.
`CompressedResourceSummary` + `CompressedSchedule.resource` —
symbolic resource evaluator; `rep n body` SCALES
`body.resource` by `n`, never expands.
`CompressedScheduleArtifact` / `VerifiedCompressedSchedule` +
generic checker; external compressed certificates (Lean
re-derives every claimed_* number).
`symbolic_rep_strict_ok` — O(|body|) sufficient check for an
n-fold repeat. The symbolic check is reps-independent BY
DESIGN: it checks the body once; soundness for the expanded
n-fold schedule is established separately in
`CompressedRepeat/SymbolicRepeatSoundness.lean`.
Grounding theorems `symbolic_rep_ok_implies_body_ok` /
`..._boundary_clean` plus accept/reject examples (incl. a
rep-1000 certificate checked without expansion).
inductiveCompressedSchedule
inductive CompressedSchedule
defCompressedSchedule.expand
def CompressedSchedule.expand : CompressedSchedule → List SysCall | .atom xs => xs | .seq blocks => seqManySchedules (blocks.map CompressedSchedule.expand) | .par blocks => parManySchedules (blocks.map CompressedSchedule.expand) | .rep n body => seqManySchedules (List.replicate n body.expand)
Reference-semantics expansion of a `CompressedSchedule`
into an explicit `List SysCall`. Uses the existing
`seqManySchedules` / `parManySchedules` combinators.
structureCompressedResourceSummary
structure CompressedResourceSummary
Resource summary: wallclock + per-kind active counts.
Computed symbolically from a `CompressedSchedule`
structure (no expansion for `rep`).
defzero
def zero : CompressedResourceSummary
The all-zero summary, identity for `seqCombine` and
`parCombine`.
defseqCombine
def seqCombine (a b : CompressedResourceSummary) : CompressedResourceSummary
Sequential combine: wallclocks SUM (back-to-back) and
every per-kind count SUMS.
defparCombine
def parCombine (a b : CompressedResourceSummary) : CompressedResourceSummary
Parallel combine: wallclock = MAX (both start at t=0;
finish at the later end); every per-kind count SUMS
(parallel still ADDS operations).
defscale
def scale (n : Nat) (r : CompressedResourceSummary) : CompressedResourceSummary
Scale: multiply every field (wallclock + every count) by
`n`. Used for `rep n body`.
defresourceOfSysCalls
def resourceOfSysCalls (xs : List SysCall) : CompressedResourceSummary
Explicit resource summary of a `List SysCall` — every field is THE
canonical `Resource/SysCallCount` counter (the single-source rule:
summaries never redefine their own walks).
defCompressedSchedule.resource
def CompressedSchedule.resource : CompressedSchedule → CompressedResourceSummary
| .atom xs => resourceOfSysCalls xs
| .seq blocks =>
(blocks.map CompressedSchedule.resource).foldr
CompressedResourceSummary.seqCombine CompressedResourceSummary.zero
| .par blocks =>
(blocks.map CompressedSchedule.resource).foldr
CompressedResourceSummary.parCombine CompressedResourceSummary.zero
| .rep n body => CompressedResourceSummary.scale n body.resourceSymbolic resource evaluator on `CompressedSchedule`.
Key property: `rep n body` is evaluated by SCALING
`body.resource` by `n` — no expansion to `n` copies.
structureCompressedScheduleArtifact
structure CompressedScheduleArtifact
Compressed-schedule artifact.
structureVerifiedCompressedSchedule
structure VerifiedCompressedSchedule
Verified compressed-schedule certificate. Carries the
symbolic resource summary AND the proof that the
expanded form passes the strict bundle.
theoremverified_compressed_schedule_of_expanded_strict_ok
theorem verified_compressed_schedule_of_expanded_strict_ok
(artifact : CompressedScheduleArtifact) (models : SystemModels)
(h : all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel
artifact.schedule.expand
models.t_react_us models.window_us models.max_per_window = true) :
∃ cert : VerifiedCompressedSchedule,
cert.artifact = artifact
∧ cert.models = models
∧ cert.resources = artifact.schedule.resource*Generic checker for compressed schedules.** If the
strict bundle holds on the expanded form, the
compressed artifact yields a verified cert with the
symbolic resources.
structureExternalCompressedScheduleCertificate
structure ExternalCompressedScheduleCertificate
External compressed-schedule certificate format.
Producers emit a `CompressedSchedule` plus their own
claimed resource numbers; Lean re-derives via the
symbolic `resource` evaluator and rejects mismatches.
defexternal_compressed_schedule_strict_ok
def external_compressed_schedule_strict_ok
(models : SystemModels) (c : ExternalCompressedScheduleCertificate) : Bool*External compressed checker.** Three derived-resource
checks (symbolic) + strict-bundle check on the expanded
form.
Lean accepts a compressed external cert iff this returns
`true`. Producers cannot lie about wallclock or
operation counts: the `claimed_*` fields are compared
against `schedule.resource.*`, NOT against producer
self-reports.
defadder_n1_compressed_atom
def adder_n1_compressed_atom : CompressedSchedule
The adder skeleton wrapped as an `atom` compressed
schedule. Just a `List SysCall` lifted into
`CompressedSchedule` — no symbolic structure.
theoremadder_n1_compressed_atom_expand
theorem adder_n1_compressed_atom_expand :
adder_n1_compressed_atom.expand = adder_n1_syscallsThe expansion of `atom` is the original SysCalls.
theoremadder_n1_compressed_atom_resource_wallclock
theorem adder_n1_compressed_atom_resource_wallclock :
adder_n1_compressed_atom.resource.wallclock_us = 48theoremadder_n1_compressed_atom_resource_syscall_count
theorem adder_n1_compressed_atom_resource_syscall_count :
adder_n1_compressed_atom.resource.syscall_count = 48theoremadder_n1_compressed_atom_resource_gate2q
theorem adder_n1_compressed_atom_resource_gate2q :
adder_n1_compressed_atom.resource.gate2q_count = 18defpython_generated_compressed_atom_example
def python_generated_compressed_atom_example :
ExternalCompressedScheduleCertificateA mock external compressed certificate. Honest claims:
accepted.
theoremadder_n1_compressed_atom_checked
theorem adder_n1_compressed_atom_checked :
external_compressed_schedule_strict_ok
adder_n1_system_models python_generated_compressed_atom_example = truedefadder_n1_repeated_3
def adder_n1_repeated_3 : CompressedSchedule
Three sequential copies of the adder skeleton via
`rep 3`.
theoremadder_n1_repeated_3_resource_wallclock
theorem adder_n1_repeated_3_resource_wallclock :
adder_n1_repeated_3.resource.wallclock_us = 144Symbolic wallclock: `3 × 48 = 144` µs — derived
WITHOUT expanding the schedule (uses
`CompressedResourceSummary.scale`).
theoremadder_n1_repeated_3_resource_gate2q
theorem adder_n1_repeated_3_resource_gate2q :
adder_n1_repeated_3.resource.gate2q_count = 54Symbolic Gate2q count: `3 × 18 = 54`.
theoremadder_n1_repeated_3_resource_syscall_count
theorem adder_n1_repeated_3_resource_syscall_count :
adder_n1_repeated_3.resource.syscall_count = 144Symbolic SysCall count: `3 × 48 = 144`.
theoremadder_n1_repeated_3_expand_wallclock
theorem adder_n1_repeated_3_expand_wallclock :
scheduleWallclockUs adder_n1_repeated_3.expand = 144The EXPANDED form's wallclock also equals 144 — the
expansion of `rep 3 body` is the seqManySchedules of 3
body copies, which the existing combinators time-shift
correctly.
defpython_generated_compressed_rep_example
def python_generated_compressed_rep_example :
ExternalCompressedScheduleCertificateAn external compressed cert that uses `rep` symbolic
structure. Honest claims; accepted.
theoremadder_n1_repeated_3_checked
theorem adder_n1_repeated_3_checked :
external_compressed_schedule_strict_ok
adder_n1_system_models python_generated_compressed_rep_example = truedefpython_bad_compressed_wallclock_example
def python_bad_compressed_wallclock_example :
ExternalCompressedScheduleCertificateA bad compressed cert with falsified wallclock claim.
theorempython_bad_compressed_wallclock_rejected
theorem python_bad_compressed_wallclock_rejected :
external_compressed_schedule_strict_ok
adder_n1_system_models python_bad_compressed_wallclock_example = falsedefpython_bad_compressed_gate2q_example
def python_bad_compressed_gate2q_example :
ExternalCompressedScheduleCertificateA bad compressed cert with falsified Gate2q count
claim.
theorempython_bad_compressed_gate2q_rejected
theorem python_bad_compressed_gate2q_rejected :
external_compressed_schedule_strict_ok
adder_n1_system_models python_bad_compressed_gate2q_example = falsedefbad_parallel_compressed_adder_schedule
def bad_parallel_compressed_adder_schedule : CompressedSchedule
A bad compressed SCHEDULE: two adder skeletons in
parallel via `CompressedSchedule.par`. Both blocks try
to allocate the same ancilla zone simultaneously; the
strict bundle rejects the expanded form (operation
capacity exceeded under `max_gate2q_active = 1`).
defbad_parallel_compressed_adder_example
def bad_parallel_compressed_adder_example :
ExternalCompressedScheduleCertificateAn external cert for the bad parallel schedule. We set
`claimed_*` to whatever the symbolic resource computes —
so that THIS test isolates the strict-bundle rejection
(not a claim mismatch).
theorembad_parallel_compressed_adder_rejected
theorem bad_parallel_compressed_adder_rejected :
external_compressed_schedule_strict_ok
adder_n1_system_models bad_parallel_compressed_adder_example = falsedefrepeat_boundary_clean
def repeat_boundary_clean (body : List SysCall) : Bool
The conservative boundary-clean condition.
defrepeat_safe_block_ok
def repeat_safe_block_ok
(models : SystemModels) (body : List SysCall) : BoolA repeat-safe block: body must pass the strict bundle AND
be boundary-clean.
defsymbolic_rep_strict_ok
def symbolic_rep_strict_ok
(models : SystemModels) (body : List SysCall) (_reps : Nat) : BoolThe symbolic repeat checker. The symbolic check is
reps-independent BY DESIGN: it checks the body once
(`O(|body|)`); the `_reps` argument deliberately does not
enter the check. Soundness for the expanded n-fold
schedule is established separately in
`CompressedRepeat/SymbolicRepeatSoundness.lean`.
structureRepeatSafeBlock
structure RepeatSafeBlock
Proof-carrying repeat-safe block. Carries the body
schedule, the system models it was certified under, the
derived wallclock, AND the boundary-clean witness.
structureRepeatedScheduleCertificate
structure RepeatedScheduleCertificate
A symbolic-repeated certificate: a repeat-safe block,
number of repetitions, and scaled resources. Does NOT
carry the expanded `List SysCall`.
defRepeatedScheduleCertificate.toCompressedSchedule
def RepeatedScheduleCertificate.toCompressedSchedule
(c : RepeatedScheduleCertificate) : CompressedScheduleLift a `RepeatedScheduleCertificate` back into the
canonical `CompressedSchedule` form (for serialization or
cross-checking).
theoremrepeated_schedule_resource_wallclock
theorem repeated_schedule_resource_wallclock
(body : List SysCall) (n : Nat) :
(CompressedSchedule.rep n (CompressedSchedule.atom body)).resource.wallclock_us
= n * scheduleWallclockUs bodySymbolic wallclock under `rep n (atom body)` =
`n × scheduleWallclockUs body`. Pure simp on the
@[simp]-tagged unfolders for `resource` plus `scale` and
`resourceOfSysCalls`.
theoremrepeated_schedule_resource_syscall_count
theorem repeated_schedule_resource_syscall_count
(body : List SysCall) (n : Nat) :
(CompressedSchedule.rep n (CompressedSchedule.atom body)).resource.syscall_count
= n * FormalRV.Resource.SysCallCount.opCountS bodytheoremrepeated_schedule_resource_gate2q
theorem repeated_schedule_resource_gate2q
(body : List SysCall) (n : Nat) :
(CompressedSchedule.rep n (CompressedSchedule.atom body)).resource.gate2q_count
= n * FormalRV.Resource.SysCallCount.countGate2q bodytheoremsymbolic_rep_ok_implies_body_ok
theorem symbolic_rep_ok_implies_body_ok
(models : SystemModels) (body : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok models body n = true) :
all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel
body
models.t_react_us models.window_us models.max_per_window = truetheoremsymbolic_rep_ok_implies_body_boundary_clean
theorem symbolic_rep_ok_implies_body_boundary_clean
(models : SystemModels) (body : List SysCall) (n : Nat)
(h : symbolic_rep_strict_ok models body n = true) :
repeat_boundary_clean body = truestructureExternalRepeatedScheduleCertificate
structure ExternalRepeatedScheduleCertificate
External symbolic-repeat certificate. Producer emits a
body, a repetition count `reps`, and claimed
repeat-scaled resources. Lean re-derives via the
SYMBOLIC `resource` evaluator — never materialises
`reps` copies.
defexternal_repeated_schedule_symbolic_ok
def external_repeated_schedule_symbolic_ok
(models : SystemModels) (c : ExternalRepeatedScheduleCertificate) : BoolExternal symbolic-repeat checker. Compares each
`claimed_*` to the SYMBOLIC `resource` (no expansion) AND
checks `symbolic_rep_strict_ok`.
theoremadder_n1_repeat_block_ok
theorem adder_n1_repeat_block_ok :
repeat_safe_block_ok adder_n1_system_models adder_n1_syscalls = trueThe adder skeleton block passes the repeat-safe checker
(it strict-passes and has no `RequestMagicState`).
theoremadder_n1_repeated_3_symbolic_ok
theorem adder_n1_repeated_3_symbolic_ok :
symbolic_rep_strict_ok adder_n1_system_models adder_n1_syscalls 3 = trueThe adder skeleton passes the symbolic-repeat checker
for `reps = 3`.
theoremadder_n1_repeated_3_expanded_strict_ok
theorem adder_n1_repeated_3_expanded_strict_ok :
all_invariants_strict_with_slot_capacity_and_freshness_ok
adder_n1_system_models.arch
adder_n1_system_models.opCap
adder_n1_system_models.slotCap
adder_n1_system_models.ancillaModel
(CompressedSchedule.rep 3 (CompressedSchedule.atom adder_n1_syscalls)).expand
adder_n1_system_models.t_react_us
adder_n1_system_models.window_us
adder_n1_system_models.max_per_window = true*Cross-check**: the symbolic checker's acceptance for
`reps = 3` matches the EXPANSION-based strict check. This
grounds the symbolic check against the existing expansion
semantics on a concrete instance.
defpython_repeated_adder_symbolic_example
def python_repeated_adder_symbolic_example :
ExternalRepeatedScheduleCertificateAn external symbolic-repeat cert claiming `1000`
repetitions. Resources scaled symbolically — no
expansion of 1000 copies.
theorempython_repeated_adder_symbolic_example_checked
theorem python_repeated_adder_symbolic_example_checked :
external_repeated_schedule_symbolic_ok
adder_n1_system_models python_repeated_adder_symbolic_example = true*The scalability headline**: Lean accepts a `rep 1000`
certificate without materialising the 1000 SysCall copies —
the symbolic check is reps-independent by design (it checks
the body once); soundness for the expanded n-fold schedule
is in `CompressedRepeat/SymbolicRepeatSoundness.lean`.
defpython_repeated_adder_bad_wallclock_example
def python_repeated_adder_bad_wallclock_example :
ExternalRepeatedScheduleCertificateBad symbolic-repeat cert with falsified wallclock claim.
theorempython_repeated_adder_bad_wallclock_rejected
theorem python_repeated_adder_bad_wallclock_rejected :
external_repeated_schedule_symbolic_ok
adder_n1_system_models python_repeated_adder_bad_wallclock_example = falsedefpython_repeated_bad_body
def python_repeated_bad_body : List SysCall
A bad body: Gate2q on ancilla site 100 before any
`RequestFreshAncilla` (the review's freshness violator
shape). Body fails strict bundle ⇒ repeat-safe checker
fails ⇒ certificate rejected.
defpython_repeated_bad_body_example
def python_repeated_bad_body_example :
ExternalRepeatedScheduleCertificateA symbolic-repeat cert wrapping the bad body. The
`claimed_*` numbers are set to the SYMBOLIC resource
values so this test isolates the BODY-validity failure
(not a claim mismatch).
theorempython_repeated_bad_body_rejected
theorem python_repeated_bad_body_rejected :
external_repeated_schedule_symbolic_ok
adder_n1_system_models python_repeated_bad_body_example = falseFormalRV.System.Artifacts.LayeredArtifactCore
FormalRV/System/Artifacts/LayeredArtifactCore.lean
FormalRV.System.Artifacts.LayeredArtifactCore — core layer-tag,
artifact, and external-certificate interface (namespace
`FormalRV.System.LayeredArtifactInterface`, shared with the
sibling `CompressedSchedule.lean`).
Lean is the trusted verifier: external tools (Python / Qiskit /
third-party) may generate schedules and certificates, but every
claimed resource number is re-derived from the SysCall list and
re-checked by Lean.
`ArtifactLayer`, `ArtifactMetadata` — layer taxonomy + metadata.
`GateArtifact` / `SurgeryArtifact` / `SysCallScheduleArtifact`
— layer-specific payloads.
`SystemModels` — the system-side parameter bundle quoted by
every system-layer certificate.
`VerifiedSysCallSchedule` +
`verified_syscall_schedule_of_strict_ok` — proof-carrying L4
certificate and the generic checker theorem.
`LayerCompiler` + wrappers around the surgery → SysCall
compilers.
`ExternalScheduleCertificate` + per-claim checkers and the
`external_schedule_strict_ok` bundle, with accept/reject
examples on the adder skeleton.
The compressed-schedule subsystem lives in the sibling module
`CompressedSchedule.lean` (which imports this file). The FTQ-VM
certificate checker (Lean-checkable certificates emitted by the
Python discrete-event VM) will also land in this folder.
inductiveArtifactLayer
inductive ArtifactLayer
The framework's layer taxonomy. Each artifact carries one
of these tags so cross-layer compilation is explicit.
structureArtifactMetadata
structure ArtifactMetadata
Lightweight artifact metadata.
structureGateArtifact
structure GateArtifact
A Gate-IR (L2) artifact. `Gate` does not derive
`Inhabited` in the framework, so neither does this
wrapper.
structureSurgeryArtifact
structure SurgeryArtifact
A surgery-gadget (L3) artifact.
structureSysCallScheduleArtifact
structure SysCallScheduleArtifact
A SysCall-schedule (L4) artifact: a finite list of
`SysCall`s plus metadata. This is the layer at which the
strict system bundle operates.
structureSystemModels
structure SystemModels
structureVerifiedSysCallSchedule
structure VerifiedSysCallSchedule
*The certified L4 artifact.** Carries a SysCall artifact,
its system models, the derived wallclock, AND proofs that
the wallclock is the foldl over `end_us` and that the
strict bundle passes.
theoremverified_syscall_schedule_of_strict_ok
theorem verified_syscall_schedule_of_strict_ok
(artifact : SysCallScheduleArtifact) (models : SystemModels)
(h : all_invariants_strict_with_slot_capacity_and_freshness_ok
models.arch models.opCap models.slotCap models.ancillaModel
artifact.syscalls
models.t_react_us models.window_us models.max_per_window = true) :
∃ cert : VerifiedSysCallSchedule,
cert.artifact = artifact
∧ cert.models = models
∧ cert.wallclock_us = scheduleWallclockUs artifact.syscalls*The generic checker theorem.** If the strict-with-
slot-capacity-and-freshness bundle holds on a SysCall
artifact under given models, a
`VerifiedSysCallSchedule` exists carrying that artifact,
those models, and the foldl-derived wallclock.
structureLayerCompiler
structure LayerCompiler (α β : Type)
A compiler from layer α-shape artifacts to layer β-shape
artifacts. Compile is a pure function; soundness
theorems live outside this record.
defsimpleSurgeryToSysCallCompiler
def simpleSurgeryToSysCallCompiler :
LayerCompiler SchedulableSurgeryGadget SysCallScheduleArtifactWrap the simple-compiler `compileSurgeryGadgetToSysCalls`
as a `LayerCompiler`. Output: `SysCallScheduleArtifact`.
deftopologySurgeryToSysCallCompiler
def topologySurgeryToSysCallCompiler :
LayerCompiler TopologySchedulableSurgeryGadget SysCallScheduleArtifactWrap the topology-aware compiler
`compileTopologySurgeryToSysCalls` as a `LayerCompiler`.
defadder_n1_syscall_artifact
def adder_n1_syscall_artifact : SysCallScheduleArtifact
The Lean-generated adder skeleton wrapped as a
`SysCallScheduleArtifact`.
defadder_n1_system_models
def adder_n1_system_models : SystemModels
The system-models bundle used by `AdderSystem`.
theoremadder_n1_artifact_verified
theorem adder_n1_artifact_verified :
∃ cert : VerifiedSysCallSchedule,
cert.artifact = adder_n1_syscall_artifact
∧ cert.models = adder_n1_system_models
∧ cert.wallclock_us
= scheduleWallclockUs adder_n1_syscall_artifact.syscalls*Adder artifact verified** — reuses
`adder_n1_strict_system_ok` and the generic checker
theorem. No `native_decide` re-run on the schedule.
structureExternalScheduleCertificate
structure ExternalScheduleCertificate
defexternal_wallclock_matches
def external_wallclock_matches (c : ExternalScheduleCertificate) : Bool
Producer's claimed wallclock equals the foldl-derived
value.
defexternal_syscall_count_matches
def external_syscall_count_matches (c : ExternalScheduleCertificate) : Bool
Producer's claimed SysCall count equals
`c.syscalls.length`.
defexternal_gate2q_count_matches
def external_gate2q_count_matches (c : ExternalScheduleCertificate) : Bool
Producer's claimed Gate2q count equals
`(syscalls.filter Gate2q).length`.
defexternal_schedule_strict_ok
def external_schedule_strict_ok
(models : SystemModels) (c : ExternalScheduleCertificate) : Bool*The full external-certificate checker.** Returns
`true` iff all three claimed resource numbers match AND
the strict-with-freshness bundle passes on the producer's
`syscalls`.
Lean accepts an external cert iff this returns `true`.
defpython_generated_adder_example
def python_generated_adder_example : ExternalScheduleCertificate
A mock external certificate: claims correspond to the
Lean-derived values for the adder skeleton. Should be
accepted.
theorempython_generated_adder_example_checked
theorem python_generated_adder_example_checked :
external_schedule_strict_ok
adder_n1_system_models python_generated_adder_example = true*External cert accepted**: Lean re-derives wallclock /
counts and verifies the strict bundle.
defpython_bad_wallclock_example
def python_bad_wallclock_example : ExternalScheduleCertificate
A bad external certificate: same `syscalls` as the good
one, but the producer LIES — claims wallclock = 1. Lean
must reject.
theorempython_bad_wallclock_example_rejected
theorem python_bad_wallclock_example_rejected :
external_schedule_strict_ok
adder_n1_system_models python_bad_wallclock_example = false*External cert rejected**: false claimed wallclock fails
`external_wallclock_matches`.
defpython_bad_gate2q_example
def python_bad_gate2q_example : ExternalScheduleCertificate
Another bad external cert: claimed Gate2q count
falsified to 1. Reuses the same syscalls and accurate
wallclock; only the Gate2q count is wrong.
theorempython_bad_gate2q_example_rejected
theorem python_bad_gate2q_example_rejected :
external_schedule_strict_ok
adder_n1_system_models python_bad_gate2q_example = falseFormalRV.System.Artifacts.LayeredArtifactInterface
FormalRV/System/Artifacts/LayeredArtifactInterface.lean
FormalRV.System.LayeredArtifactInterface — umbrella for the
shared multi-layer artifact and certificate interface.
Lean is the trusted verifier: both Lean-generated and external
(Python / Qiskit / third-party) circuits, schedules, and
certificates target the SAME checker interfaces; external output
is always re-derived and re-checked by Lean.
Content lives in two sibling modules that declare the same
namespace, so all existing fully-qualified references keep
working:
`LayeredArtifactCore` — layer tags, artifact wrappers,
`SystemModels`, `VerifiedSysCallSchedule` + generic checker,
`LayerCompiler`, external SysCall-schedule certificates.
`CompressedSchedule` — hierarchical compressed schedules:
expand/resource semantics, compressed + symbolic-repeat
certificates and the `symbolic_rep_strict_ok` checker.
This file only re-exports; add new declarations to the pieces.
(no documented top-level declarations)
FormalRV.System.Bounds.HardwareSensitivity
FormalRV/System/Bounds/HardwareSensitivity.lean
FormalRV.System.HardwareSensitivity — the resource lower bound as a function of the FULL set of
hardware parameters, with a proven SENSITIVITY (monotonicity) theorem for EACH one, applied to
BOTH Gidney papers.
## Hardware parameters (complete set)
d — code distance → physical qubits per logical patch `2(d+1)²`
tReact — decoder reaction time (DECODING SPEED)
tMeas — logical measurement time (MEASUREMENT TIME)
prod — magic-state production time
fq — factory footprint (qubits)
Q — total physical qubits (ARCHITECTURE SIZE)
nDec — parallel decoders (DECODER PARALLELISM)
maxPar — max parallel operations (MAX PARALLEL PHYSICAL OPERATIONS)
routeLat — routing latency (ROUTING LATENCY)
## The lower bound and its sensitivity
The runtime lower bound is the MAX of four resource/causal floors (each a packing/critical-path
impossibility, cf. `ScheduleLowerBound.magic_spacetime_floor` / `.causal_chain4`):
magicFloor = K·fq·prod / Q (magic-state spacetime; sens. Q, fq, prod)
decoderFloor = K·tReact / nDec (decoder throughput; sens. tReact, nDec)
parFloor = K·(tMeas+routeLat) / maxPar (op-slot throughput; sens. tMeas, routeLat, maxPar)
depthFloor = depth·(tMeas+tReact) (causal critical path; sens. depth, tMeas, tReact)
EVERY hardware parameter appears, and each floor is PROVEN monotone in its parameters — increasing
in every latency (`*_mono_*`), decreasing in every capacity (`*_anti_*`), physical qubits
increasing in `d`. So the bound is genuinely sensitive to all of decoding speed, architecture
size, routing latency, measurement time, and max parallelism — none is silently dropped.
defmagicFloorN
def magicFloorN (K fq prod Q : Nat) : Nat
defdecoderFloorN
def decoderFloorN (K tReact nDec : Nat) : Nat
defparFloorN
def parFloorN (K opTime maxPar : Nat) : Nat
defdepthFloorN
def depthFloorN (depth tMeas tReact : Nat) : Nat
defphysQubitsN
def physQubitsN (L d : Nat) : Nat
theoremdecoderFloor_mono_tReact
theorem decoderFloor_mono_tReact (K nDec : Nat) {t t' : Nat} (h : t ≤ t') :
decoderFloorN K t nDec ≤ decoderFloorN K t' nDec*DECODING SPEED (`tReact`)** — a slower decoder raises the decoder-throughput floor …
theoremdepthFloor_mono_tReact
theorem depthFloor_mono_tReact (depth tMeas : Nat) {t t' : Nat} (h : t ≤ t') :
depthFloorN depth tMeas t ≤ depthFloorN depth tMeas t'… and the causal critical-path floor.
theoremdecoderFloor_anti_nDec
theorem decoderFloor_anti_nDec (K t : Nat) {n n' : Nat} (hpos : 0 < n) (h : n ≤ n') :
decoderFloorN K t n' ≤ decoderFloorN K t n*DECODER PARALLELISM (`nDec`)** — more decoders LOWER the floor (anti-monotone).
theoremmagicFloor_anti_Q
theorem magicFloor_anti_Q (K fq prod : Nat) {Q Q' : Nat} (hpos : 0 < Q) (h : Q ≤ Q') :
magicFloorN K fq prod Q' ≤ magicFloorN K fq prod Q*ARCHITECTURE SIZE (`Q`)** — a larger device LOWERS the magic-state floor (anti-monotone:
more space → less time).
theoremmagicFloor_mono_prod
theorem magicFloor_mono_prod (K fq Q : Nat) {p p' : Nat} (h : p ≤ p') :
magicFloorN K fq p Q ≤ magicFloorN K fq p' Q*PRODUCTION TIME (`prod`)** — slower factories raise the magic-state floor.
theoremmagicFloor_mono_fq
theorem magicFloor_mono_fq (K prod Q : Nat) {f f' : Nat} (h : f ≤ f') :
magicFloorN K f prod Q ≤ magicFloorN K f' prod Q*FACTORY FOOTPRINT (`fq`)** — larger factories raise the magic-state floor.
theoremparFloor_mono_opTime
theorem parFloor_mono_opTime (K maxPar : Nat) {o o' : Nat} (h : o ≤ o') :
parFloorN K o maxPar ≤ parFloorN K o' maxPar*ROUTING LATENCY (`routeLat`) & MEASUREMENT TIME (`tMeas`)** — both enter `opTime`, so a slower
operation raises the op-slot floor.
theoremdepthFloor_mono_tMeas
theorem depthFloor_mono_tMeas (depth tReact : Nat) {m m' : Nat} (h : m ≤ m') :
depthFloorN depth m tReact ≤ depthFloorN depth m' tReact*MEASUREMENT TIME (`tMeas`)** also raises the causal critical-path floor.
theoremparFloor_anti_maxPar
theorem parFloor_anti_maxPar (K o : Nat) {p p' : Nat} (hpos : 0 < p) (h : p ≤ p') :
parFloorN K o p' ≤ parFloorN K o p*MAX PARALLEL OPERATIONS (`maxPar`)** — more parallelism LOWERS the op-slot floor.
theoremphysQubits_mono_d
theorem physQubits_mono_d (L : Nat) {d d' : Nat} (h : d ≤ d') :
physQubitsN L d ≤ physQubitsN L d'*CODE DISTANCE (`d`)** — a larger distance raises the physical-qubit count `L·2(d+1)²`.
structureHW
structure HW
defHW.timeLB
def HW.timeLB (h : HW) (K depth : Nat) : Nat
defge2021
def ge2021 : HW
GE2021 hardware (8 h / 20M qubits): d=27, 10 µs reaction, 27 µs measure, CCZ factory
2565 qubits / 12000 µs, 20M qubits.
defgidney2025
def gidney2025 : HW
Gidney 2025 hardware (under a week / <1M qubits): d=25, 10 µs reaction, 25 µs measure,
1M qubits; same CCZ factory spec as GE2021 (`Params.RSA2048`).
defge2021_K
def ge2021_K : Nat
defgidney2025_K
def gidney2025_K : Nat
theoremboth_papers
theorem both_papers :
magicFloorN ge2021_K ge2021.fq ge2021.prod 3600000000 = 22425149
∧ magicFloorN gidney2025_K gidney2025.fq gidney2025.prod 3600000000 = 55575000
∧ physQubitsN 6189 ge2021.d = 9704352
∧ physQubitsN 6189 gidney2025.d = 8367528*★ Both papers, instantiated ★.** The magic-state spacetime floor (qubit·hours) and the
distance-driven data-qubit count, for GE2021 (d=27, K≈2.62×10⁹) and Gidney 2025 (d=25,
K≈6.5×10⁹). UNITS CAVEAT: the 4th argument of `magicFloorN` is its `Q` (architecture-size)
slot, here REPURPOSED as `3 600 000 000` µs-per-hour — so `K·fq·prod / 3.6×10⁹` is the floor
`K·fq·prod` (qubit·µs) converted to qubit·HOURS, not a runtime on a 3.6×10⁹-qubit device.
Floors: 22.4M and 55.6M qubit-hours; the reported spacetimes (160M and 168M qubit-hours) sit
~7× and ~3× above their OWN floors — the framework works for both, and each is near its
hardware-determined limit.
theoremmagicFloor_matches_rsa2048
theorem magicFloor_matches_rsa2048 :
magicFloorN ge2021_K ge2021.fq ge2021.prod 3600000000
= ScheduleLowerBound.rsa2048_floor_qubit_hours*Cross-reference (dedup):** the magic-state floor computed here for GE2021 is the SAME number
as `ScheduleLowerBound.rsa2048_floor_qubit_hours` — the two "22 425 149 qubit-hours" literals are
proven equal rather than independently asserted.
FormalRV.System.Bounds.NaiveSchedule
FormalRV/System/Bounds/NaiveSchedule.lean
FormalRV.System.NaiveSchedule — the FULL device schedule for a computation of ANY size, defined
RECURSIVELY (not enumerated concretely), and PROVEN valid for all sizes.
Part of the unified FT-scheduling framework — see `FormalRV.System.FTFramework` for the single
entry point. This module proves schedule VALIDITY on `DSchedule`; its `ResourceEstimate` sibling
is `FormalRV.System.NaiveUpperBound` (resource-number upper bound), connected via `ScheduleBounds`.
Instead of building the ~10⁹-operation RSA-2048 schedule by hand, define the most NAIVE strategy
— do everything ONE OPERATION AT A TIME (fully serial) — as a recursive function of the
operation count `M`, and prove `scheduleValid dev (naiveSchedule M)` for ALL `M` by induction.
Naïveté is the point: a serial schedule has NO two operations overlapping in time, so every
conflict / capacity / decoder-queue concern is trivially satisfied — which is exactly why
correctness is provable at any scale. No parallelism, no tight space packing (one reused
resource region); optimization is future work ON TOP of this.
Hence `naiveSchedule_valid : ∀ M, adequate dev → scheduleValid dev (naiveSchedule M) = true`, so
the RSA-2048 device schedule is `naiveSchedule (opCount)`, valid by this one theorem — the full
schedule is defined mathematically and verified for all sizes without enumeration.
defnaiveOp
def naiveOp (k : Nat) : DeviceOp
The `k`-th operation: a unit-duration op in window `[k, k+1)` on the single reused resource
region `[0]`, cycling prepMagic → consumeMagic → decode by `k % 3`. No dep edges (the WAIT is
the global total time order — see `naiveFrom_total_order`).
defnaiveFrom
def naiveFrom (s : Nat) : Nat → DSchedule | 0 => [] | M + 1 => naiveOp s :: naiveFrom (s + 1) M
`M` serial ops at times `s, s+1, …, s+M-1`.
defnaiveSchedule
def naiveSchedule (M : Nat) : DSchedule
The full naive schedule for `M` operations (starting at time 0).
theoremnaiveFrom_begin_ge
theorem naiveFrom_begin_ge : ∀ (s M : Nat) (o : DeviceOp), o ∈ naiveFrom s M → s ≤ o.begin_t | _, 0, o, h => by simp [naiveFrom] at h | s, M + 1, o, h =>
theoremnaiveFrom_footprint
theorem naiveFrom_footprint : ∀ (s M : Nat) (o : DeviceOp), o ∈ naiveFrom s M → o.footprint = [0] | _, 0, o, h => by simp [naiveFrom] at h | s, M + 1, o, h =>
theoremnaiveFrom_dur
theorem naiveFrom_dur : ∀ (s M : Nat) (o : DeviceOp), o ∈ naiveFrom s M → o.dur_t = 1 | _, 0, o, h => by simp [naiveFrom] at h | s, M + 1, o, h =>
theoremnaiveFrom_deps
theorem naiveFrom_deps : ∀ (s M : Nat) (o : DeviceOp), o ∈ naiveFrom s M → o.deps = [] | _, 0, o, h => by simp [naiveFrom] at h | s, M + 1, o, h =>
theoremhead_no_conflict
theorem head_no_conflict (s M : Nat) :
(naiveFrom (s + 1) M).all (fun o => ! (naiveOp s).conflictsWith o) = truetheoremconflictFree_naiveFrom
theorem conflictFree_naiveFrom : ∀ (s M : Nat), conflictFree (naiveFrom s M) = true | _, 0 => rfl | s, M + 1 =>
*★ `naiveFrom s M` is conflict-free for ALL `M` ★** — the serial schedule never has two ops
sharing a time, hence no space-time conflict. By induction on `M`.
theoremnaiveFrom_filter_empty
theorem naiveFrom_filter_empty (P : DeviceOp → Bool) (t : Nat)
(hP : ∀ o, P o = true → o.activeAt t = true) :
∀ (s M : Nat), t < s → (naiveFrom s M).filter P = []theoremnaiveFrom_filter_le_one
theorem naiveFrom_filter_le_one (P : DeviceOp → Bool) (t : Nat)
(hP : ∀ o, P o = true → o.activeAt t = true) :
∀ (s M : Nat), ((naiveFrom s M).filter P).length ≤ 1theoremnaiveFrom_atMostOneActive
theorem naiveFrom_atMostOneActive (t s M : Nat) :
((naiveFrom s M).filter (fun o => o.activeAt t)).length ≤ 1theoremdecoderActive_naive_le_one
theorem decoderActive_naive_le_one (t s M : Nat) :
((naiveFrom s M).filter (fun o => o.isDecode && o.activeAt t)).length ≤ 1theoremmapsum_footprint_le_one
theorem mapsum_footprint_le_one : ∀ (L : List DeviceOp), L.length ≤ 1 →
(∀ o ∈ L, o.footprint.length = 1) →
(L.map (fun o => o.footprint.length)).sum ≤ 1
| [], _, _ => by simp
| [o], _, h2 =>theoremactiveFootprintSize_naive_le_one
theorem activeFootprintSize_naive_le_one (s M t : Nat) :
activeFootprintSize (naiveFrom s M) t ≤ 1defadequate
def adequate (dev : Device) : Prop
A device that admits the naive schedule: ≥ 1 resource, ≥ 1 decoder, reaction ≥ 1.
theoremcapacityRespected_naive
theorem capacityRespected_naive (dev : Device) (M : Nat) (h : 1 ≤ dev.totalResources) :
capacityRespected dev (naiveSchedule M) = truetheoremdecoderQueueRespected_naive
theorem decoderQueueRespected_naive (dev : Device) (M : Nat) (h : 1 ≤ dev.nDecoders) :
decoderQueueRespected dev (naiveSchedule M) = truetheoremreactionRespected_naive
theorem reactionRespected_naive (dev : Device) (M : Nat) (h : 1 ≤ dev.reactionTime) :
reactionRespected dev (naiveSchedule M) = truetheoremdepsRespected_naive
theorem depsRespected_naive (M : Nat) : depsRespected (naiveSchedule M) = true
Dependency check — VACUOUS for the naive schedule: every `naiveOp` has `deps = []`, so the
quantifier ranges over empty lists and the check passes trivially. It is part of the validity
bundle for completeness; the real ordering guarantee is `naiveFrom_total_order` (§6).
theoremnaiveSchedule_valid
theorem naiveSchedule_valid (dev : Device) (M : Nat) (hdev : adequate dev) :
scheduleValid dev (naiveSchedule M) = true*★ THE HEADLINE ★** — for ANY operation count `M`, the recursively-defined naive serial
schedule is a VALID device schedule (all five concerns), on any adequate device. The full
(e.g. RSA-2048) schedule is thus defined and verified for all sizes without enumeration.
theoremnaiveFrom_total_order
theorem naiveFrom_total_order (s M : Nat) (o1 o2 : DeviceOp)
(h1 : o1 ∈ naiveFrom s M) (hlt : o1.begin_t < o2.begin_t) :
o1.end_t ≤ o2.begin_t*The wait law, structurally.** In the serial schedule any earlier op (smaller `begin_t`)
COMPLETES before any later op begins — the strongest produce-before-consume guarantee (so e.g.
a `consumeMagic` at time `k+1` always follows the `prepMagic` at time `k`).
defrsa2048_opCount
def rsa2048_opCount : Nat
The number of device operations for windowed RSA-2048: three (prepare → teleport → decode) per
Toffoli, with the verified Toffoli budget (`RSA2048.magicBudget = 2 622 824 448`) — i.e.
`7 868 473 344` ops.
theoremrsa2048_opCount_value
theorem rsa2048_opCount_value : rsa2048_opCount = 7868473344
theoremrsa2048_naive_schedule_valid
theorem rsa2048_naive_schedule_valid (dev : Device) (hdev : adequate dev) :
scheduleValid dev (naiveSchedule rsa2048_opCount) = true*★ The full ~8×10⁹-operation RSA-2048 device schedule is VALID ★** — defined recursively as
`naiveSchedule rsa2048_opCount` (never enumerated) and proven valid by the parametric headline,
on any adequate device. This is the naive (serial, one-at-a-time) strategy: provably correct at
full scale, the baseline on which parallel/space-packed optimizations can be built.
FormalRV.System.Bounds.NaiveUpperBound
FormalRV/System/Bounds/NaiveUpperBound.lean
FormalRV.System.NaiveUpperBound — a NAIVE, STANDARD, MECHANICAL schedule with
a VERIFIED resource upper bound, and the GAP to each paper's reported estimate.
Part of the unified FT-scheduling framework — see `FormalRV.System.FTFramework` for the single
entry point. This module bounds resources on `ResourceEstimate` (the cost-model view); its
`DSchedule` sibling is `FormalRV.System.NaiveSchedule` (peak-footprint validity for all sizes).
`ScheduleBounds.resource_bracket` brackets the lower bound (`ScheduleLowerBound`) and this
upper bound around one schedule's workload.
Motivation. We cannot verify that a paper's reported
resource is OPTIMAL (= a lower bound), because the optimal PPM / decoder /
qubit-routing schedule on the proposed hardware is unknown — finding it is
itself a hard research problem. But we can help the author from the OTHER
side:
1. construct a naive, standard, mechanical schedule;
2. PROVE a verifiable UPPER BOUND on its resources — the rigor is that the
naive schedule is FEASIBLE (satisfies the system invariants) and its peak
demand never exceeds a static footprint FOR ANY problem size (induction);
3. QUANTIFY the GAP between that verified ceiling and the paper's (smaller,
optimized, unverified) reported number.
optimal_cost ≤ naive_upper_bound (feasibility ⇒ we certify this side)
reported_cost ≤ naive_upper_bound (the paper sits BELOW our ceiling)
gap = naive_upper_bound − reported_cost (the unverified optimization)
COST RULE IS A PLUG-IN.
The naive schedule's routing/ancilla rule is NOT hardcoded here: it is the
framework's `surfaceModel` plug-in (`Framework/CostModel.lean`), run
sequentially. Choosing surface vs qLDPC is a PARAMETER — swap `surfaceModel`
for `qldpcModel` and the ceiling recomputes with the weight-scaling ancilla
rule, no code change. Verification stays at the general level
(`estimateWith_{time,qubits}`, proven `∀ model`); the code-specific rule is a
framework instance, never special-cased outside.
No Mathlib. Pure Nat / Bool. No `sorry`, no `axiom`.
defnaiveEstimate
def naiveEstimate (hw : Hardware) (w : Workload) (c : QECCode) (factory : Nat) :
ResourceEstimateThe naive schedule's resource estimate, via the framework's `surfaceModel`
plug-in. `op_weight` is irrelevant under the surface model (its ancilla rule
ignores it — surface routing does not scale with operator weight), so we pass
0; `parallel = 1` is the sequential schedule.
theoremnaive_time
theorem naive_time (hw : Hardware) (w : Workload) (c : QECCode) (factory : Nat) :
(naiveEstimate hw w c factory).time_us_tenths
= w.n_toff * c.d * hw.cycle_time_us_tenthsNaive wallclock = n_toff · d · t_cycle (sequential critical path; the surface
model charges `tauToff = d` cycles per Toffoli).
theoremnaive_qubits
theorem naive_qubits (hw : Hardware) (w : Workload) (c : QECCode) (factory : Nat) :
(naiveEstimate hw w c factory).qubits
= w.n_logical * (2 * physPerLogical c) + factoryNaive qubit footprint = n_logical · (2·phys) + factory: the standing ~2×
surface patch (data + in-patch syndrome + equal-area routing region, all a
per-logical LAYOUT cost) plus the factory. Under the surface cost model both
operation-ancilla tags (syndrome, surgery) are 0 — the audit-relevant ancilla
is the standing footprint, captured in `physPer`.
defnaivePeak
def naivePeak (footprint : Nat) : Nat → Nat | 0 => 0 | k + 1 => max footprint (naivePeak footprint k)
Peak physical-qubit demand after `k` sequential Toffoli steps. Each step
uses the SAME footprint (sequential: one Toffoli active), so the running
peak is a fold of a constant.
theoremnaivePeak_le_footprint
theorem naivePeak_le_footprint (footprint k : Nat) :
naivePeak footprint k ≤ footprintFor every problem size `k`, the naive schedule's peak qubit demand is ≤ the
static footprint — true by construction (`naivePeak` folds the constant
`footprint`). What it certifies is feasibility: the sequential schedule
fits inside the footprint at every size, so the footprint is an achievable
ceiling on the qubit count.
theoremnaive_peak_within_estimate
theorem naive_peak_within_estimate
(hw : Hardware) (w : Workload) (c : QECCode) (factory k : Nat) :
naivePeak ((naiveEstimate hw w c factory).qubits) k
≤ (naiveEstimate hw w c factory).qubits`naivePeak_le_footprint` specialised to the naive estimate's own qubit
figure (likewise true by construction).
defnaiveMakespan
def naiveMakespan (hw : Hardware) (d k : Nat) : Nat
Naive sequential makespan after `k` Toffoli steps = k · d · t_cycle — the
LONGEST any schedule of these steps can take (no parallelism), hence an upper
bound on the optimal (parallel) makespan. At `k = w.n_toff` it equals the
naive estimate's wallclock.
theoremnaiveMakespan_at_full
theorem naiveMakespan_at_full
(hw : Hardware) (w : Workload) (c : QECCode) (factory : Nat) :
naiveMakespan hw c.d w.n_toff = (naiveEstimate hw w c factory).time_us_tenthsexample(example)
example : checkAll baseInvariants demoCtx = true
defge2021_hw
def ge2021_hw : Hardware
GE2021 hardware: 1 μs cycle.
defge2021_work
def ge2021_work : Workload
GE2021 workload: ≈ 2.7×10⁹ Toffolis over ≈ 6200 logical qubits (the canonical
`Params.RSA2048` constants).
defge2021_code
def ge2021_code : QECCode
GE2021 surface patch [[1568, 1, 27]].
defge2021_naive
def ge2021_naive : ResourceEstimate
The naive ceiling for GE2021 under the `surfaceModel` plug-in, factory folded
out (`0`) so the qubit figure is the pure data + 2× routing ceiling.
defge2021_reported_qubits
def ge2021_reported_qubits : Nat
GE2021 reported headline: 20 million physical qubits.
defge2021_reported_time_us_tenths
def ge2021_reported_time_us_tenths : Nat
GE2021 reported headline: 8 hours, in tenths-of-μs (8·3600·10⁶·10 = 288×10⁹).
example(example)
example : ge2021_naive.qubits = 19_443_200
Naive ceiling = 6200 · (2·1568) = 19,443,200 qubits (surface `physPer` =
2·physPerLogical = 3136 per logical).
example(example)
example : ge2021_naive.qubits ≤ ge2021_reported_qubits
The naive ceiling sits just below the reported 20M total…
example(example)
example : ge2021_reported_qubits - ge2021_naive.qubits ≤ 600_000
…within ~3% — the residual (≈ 0.56M) is the magic-factory footprint our
naive model folds out. So GE2021's reported qubit count IS essentially the
verified surface-model area ceiling: NO unverified qubit-side optimization.
example(example)
example : ge2021_naive.time_us_tenths = 729_000_000_000
Naive sequential time ceiling = 2.7×10⁹ · 27 · 1 μs = 72.9×10⁹ μs ≈ 20.25 h
(here in tenths-of-μs: 729×10⁹).
example(example)
example : ge2021_reported_time_us_tenths ≤ ge2021_naive.time_us_tenths
The reported 8 h sits BELOW the naive sequential ceiling — the paper's
schedule is faster than dumb sequential execution.
example(example)
example : 2 * ge2021_reported_time_us_tenths ≤ ge2021_naive.time_us_tenths
The gap is between 2× and 3×: GE2021's reported wallclock is ~2.5× under our
verified naive ceiling. That speed-up comes from reaction-limited pipelining
of the Toffoli critical path — an optimization we do NOT verify. The gap
makes exactly this factor explicit.
example(example)
example : ge2021_naive.time_us_tenths ≤ 3 * ge2021_reported_time_us_tenths
FormalRV.System.Bounds.ScheduleAdvance
FormalRV/System/Bounds/ScheduleAdvance.lean
FormalRV.System.ScheduleAdvance — beating the naive baseline (an advanced scheduler), the WALL it
hits, and applying the framework to OTHER papers.
## Advanced scheduler: parallel magic-state factories
The naive baseline (`Audit/GidneyEkera2021/Verifier`, Part B: `naiveWallclockHours`) is fully
serial — one factory, ~8782 hours. The first
real optimization is to run `F` factories IN PARALLEL (disjoint footprints): the magic supply
drops to `⌈K/F⌉ · production_us` (`MagicScheduleComplete.magicSupplyTimeUs`). We show:
a concrete 2-factory schedule is VALID and produces 2 magic states in ONE production window
instead of two (real parallelism, proven conflict-free);
at `F = 1093` factories the magic supply is `≤ 8 hours` — MATCHING the paper, a ~1098×
speedup over the naive 8782 hours.
## The WALL
Parallelizing factories cannot go below the **spacetime floor** (`ScheduleLowerBound`,
`Q·T ≥ K·fq·prod`): more factories cost more qubits, and the paper already sits ~7× above the
floor. Beyond matching the magic supply to the LOGICAL DEPTH, further speedup requires
parallelizing the data-dependent logical operations themselves (the accumulator chain) — which
needs the circuit's detailed dependency structure (the time-optimal scheme). That is the wall:
the magic-supply optimization is exhausted once `F` meets the depth; the rest is detailed circuit
scheduling.
## Other papers
The lower bound and baseline are PARAMETRIC, so they instantiate per paper. We instantiate the
floor for Babbush-2026 ECC-256 (`90 000 000` Toffolis) as a demonstration.
defparallelTwoFactories
def parallelTwoFactories : DSchedule
*A 2-factory parallel schedule is valid and genuinely parallel.** Two `prepMagic` ops run in
the SAME window `[0,2)` on DISJOINT footprints (factories A=`{100,101}`, B=`{102,103}`), so the
schedule is conflict-free — two magic states produced in ONE production window, not two.
defparDev
def parDev : Device
theoremparallelTwoFactories_valid
theorem parallelTwoFactories_valid : scheduleValid parDev parallelTwoFactories = true
theoremparallelTwoFactories_parallel
theorem parallelTwoFactories_parallel :
opsTimeOverlap parallelTwoFactories[0]! parallelTwoFactories[1]! = true
∧ conflictFree parallelTwoFactories = trueBoth factories overlap in time (genuine parallelism) yet do not conflict.
theoremparallel_1093_within_8h
theorem parallel_1093_within_8h :
magicSupplyTimeUs 2622824448 1093 ccz_spec_qianxu ≤ 8 * 3600000000
∧ 7 * 3600000000 ≤ magicSupplyTimeUs 2622824448 1093 ccz_spec_qianxu*★ Parallel factories hit the paper's runtime ★** — with `F = 1093` CCZ factories, the magic
supply for the windowed RSA-2048 budget is `≤ 8 hours` (`28 795 884 000 µs`), versus the naive
serial `8782` hours — a ~1098× speedup that MATCHES the paper.
theoremparallel_speedup
theorem parallel_speedup :
1000 * magicSupplyTimeUs 2622824448 1093 ccz_spec_qianxu
≤ magicSupplyTimeUs 2622824448 1 ccz_spec_qianxuSpeedup over the naive serial baseline (F = 1): the 1093-factory supply is `> 1000×` faster.
theoremparallel_supply_above_floor
theorem parallel_supply_above_floor :
-- the 1093-factory magic supply, as qubit·µs over the data+factory device, is ≥ the floor
ScheduleLowerBound.rsa2048_floor_qubit_us
≤ (9633792 + 1093 * 2565) * magicSupplyTimeUs 2622824448 1093 ccz_spec_qianxu*The wall, checked at the 1093-factory point.** This is ONE NUMERIC INSTANCE, not a
universal statement: it verifies that the 1093-factory configuration's spacetime
((data + factory qubits) × supply time) stays at or above the RSA-2048 magic-state floor.
The universal impossibility — NO schedule beats `Q·T ≥ K·fq·prod` — is
`ScheduleLowerBound.magic_spacetime_floor`. The paper already sits ~7× above that floor; the
remaining speedup is not a magic-supply problem but a LOGICAL-DEPTH problem (parallelizing the
data-dependent operations), which needs the circuit's detailed dependency structure.
defbabbush_ecc256_floor_qubit_hours
def babbush_ecc256_floor_qubit_hours : Nat
*Babbush-2026 ECC-256 magic-state floor.** The lower bound `magic_spacetime_floor` is
parametric, so it instantiates per paper. For Babbush ECC-256's `90 000 000` Toffolis (with a
CCZ-style factory: `2565` qubits, `12000 µs`), the spacetime floor is `≈ 769 500` qubit-hours —
a hard limit for that computation too. (The concrete factory spec should be the paper's own;
here we use the cited qianxu CCZ factory as a stand-in to show the framework generalizes.)
theorembabbush_ecc256_floor_value
theorem babbush_ecc256_floor_value : babbush_ecc256_floor_qubit_hours = 769500
defnaiveSerialHours
def naiveSerialHours (K : Nat) : Nat
The naive serial baseline applies to ANY Toffoli count `K`: runtime `= K · 12054 µs`
(12 000 µs CCZ window + 27 µs teleport + 27 µs decode at d=27; derived as
`Audit/GidneyEkera2021/Verifier.perToffoliUs`). For
Babbush ECC-256 (`K = 90 000 000`) that is `≈ 301` hours serially — which the paper's parallel
construction (500 000 qubits, ~20 min) beats by exploiting parallelism, exactly as for RSA.
theorembabbush_ecc256_naive_hours
theorem babbush_ecc256_naive_hours : naiveSerialHours 90000000 = 301
FormalRV.System.Bounds.ScheduleBounds
FormalRV/System/Bounds/ScheduleBounds.lean
FormalRV.System.ScheduleBounds — bracket ONE resource on ONE schedule (`DSchedule`).
The two bound efforts live on disjoint data models:
UPPER bound: `NaiveUpperBound.naivePeak_le_footprint` — a sequential schedule's peak
qubit demand ≤ its static footprint, on `ResourceEstimate`.
LOWER bound: `ScheduleLowerBound.magic_spacetime_floor` / `workload_le` —
`K·fq·prod ≤ workload ≤ Q·T`, on `DSchedule`.
Here both are stated on the SAME `DSchedule` (the canonical schedule object: recursively defined
and proven valid for all sizes), so they genuinely BRACKET the resource the schedule books:
K · fq · prod ≤ workload sched ≤ Q · T (`resource_bracket`)
schedulePeak (naiveSchedule M) ≤ totalResources (`naive_peak_le_total`, the
`DSchedule` analogue of
`naivePeak_le_footprint`).
defschedulePeak
def schedulePeak (sched : DSchedule) : Nat
Peak active footprint over the schedule's boundary times — the standing qubit demand.
theoremfoldl_max_le
private theorem foldl_max_le : ∀ (L : List Nat) (acc c : Nat),
acc ≤ c → (∀ x ∈ L, x ≤ c) → L.foldl max acc ≤ c
| [], acc, c, ha, _ => ha
| x :: xs, acc, c, ha, h =>theoremnaive_peak_le_one
theorem naive_peak_le_one (M : Nat) : schedulePeak (naiveSchedule M) ≤ 1
*UPPER bracket (naive ≤ 1)** — the naive serial schedule keeps at most one op live, so its peak
footprint is `≤ 1`, for ALL sizes (the `DSchedule` analogue of `naivePeak_le_footprint`).
theoremnaive_peak_le_total
theorem naive_peak_le_total (dev : Device) (M : Nat) (h : 1 ≤ dev.totalResources) :
schedulePeak (naiveSchedule M) ≤ dev.totalResourcesThe naive schedule's peak demand never exceeds the device footprint (capacity), for ALL sizes.
theoremresource_bracket
theorem resource_bracket (sched : DSchedule) (T Q fq prod : Nat)
(hfit : ∀ o ∈ sched, o.end_t ≤ T)
(hcap : ∀ t ∈ Finset.range T, activeFootprintSize sched t ≤ Q)
(hf : ∀ o ∈ sched, fq ≤ o.footprint.length)
(hd : ∀ o ∈ sched, prod ≤ o.dur_t) :
sched.length * (fq * prod) ≤ workload sched ∧ workload sched ≤ Q * T*★ THE BOUND UNIFICATION ★** — on any schedule that fits horizon `T`, respects capacity `Q`,
and whose ops each reserve ≥ `fq` qubits for ≥ `prod` time, the footprint-time the schedule
books is squeezed between the magic-state floor and the device spacetime:
(#ops) · fq · prod ≤ workload sched ≤ Q · T.
The left inequality is the impossibility floor (`workload_ge_of_uniform`), the right is the
packing ceiling (`workload_le`) — one chain on one object.
FormalRV.System.Bounds.ScheduleLowerBound
FormalRV/System/Bounds/ScheduleLowerBound.lean
FormalRV.System.ScheduleLowerBound — IMPOSSIBILITY (lower-bound) results for device schedules,
derived from the system invariants + causality. No schedule, however clever, can beat these.
1. **Causal-chain bound** (`causal_two`, `causal_chain4`): the user's "a T-state must be distilled
before injection; syndromes must be measured before decoding" — causally-dependent ops cannot
overlap, so their durations ADD. A distill → inject → measure → decode chain cannot be
compressed below the sum of its four stage times.
2. **Spacetime packing bound** (`workload_le`, `magic_spacetime_floor`): the BIG one. In a
capacity-`Q` schedule over horizon `T`, the total reserved footprint-time (`workload`) is
`≤ Q · T` — disjoint reservations pack into the spacetime box. Producing `K` magic states
costs `≥ K · factory_qubits · production_us` of footprint-time, so `Q · T ≥ K · fq · prod`,
a floor NO schedule can beat. At GE2021 numbers (`K = 2 622 824 448`, `fq = 2565`,
`prod = 12000 µs`) the floor is ≈ `2.24×10⁷` qubit-hours: the paper (`1.6×10⁸`) is ~7× above,
the naive baseline (`8.46×10¹⁰`) ~3774× above.
theoremcausal_two
theorem causal_two (a b : DeviceOp) (h : a.end_t ≤ b.begin_t) :
a.begin_t + a.dur_t + b.dur_t ≤ b.end_t*Two causally-dependent ops cannot overlap.** If `a` must finish before `b` begins, their
durations ADD — `b` finishes no earlier than `a.begin + a.dur + b.dur`.
theoremcausal_chain4
theorem causal_chain4 (distill inject meas decode : DeviceOp)
(h1 : distill.end_t ≤ inject.begin_t) (h2 : inject.end_t ≤ meas.begin_t)
(h3 : meas.end_t ≤ decode.begin_t) :
distill.begin_t + distill.dur_t + inject.dur_t + meas.dur_t + decode.dur_t ≤ decode.end_t*A distill → inject → measure → decode causal chain cannot be compressed.** The decode
finishes no earlier than the start plus ALL four stage durations. This is exactly the user's
causality: a T-state must be distilled before injection, and syndromes measured before decoding;
none of these stages can overlap.
defopWork
def opWork (o : DeviceOp) : Nat
The footprint-time "work" of one op (resources × duration).
defworkload
def workload (sched : DSchedule) : Nat
Total footprint-time reserved by a schedule.
defspacetimeUsed
def spacetimeUsed (sched : DSchedule) (T : Nat) : Nat
Spacetime consumed up to horizon `T`: the per-instant active footprint, summed over time.
theoremactiveFootprintSize_eq_indicator
theorem activeFootprintSize_eq_indicator (sched : DSchedule) (t : Nat) :
activeFootprintSize sched t
= (sched.map (fun o => if o.activeAt t then o.footprint.length else 0)).sum`activeFootprintSize` as an indicator sum over ALL ops (non-active contribute 0).
theoremsum_range_listmap
theorem sum_range_listmap (T : Nat) {α : Type _} (L : List α) (g : Nat → α → Nat) :
∑ t ∈ Finset.range T, (L.map (fun a => g t a)).sum
= (L.map (fun a => ∑ t ∈ Finset.range T, g t a)).sumSwap a `Finset.range` sum with a `List.map` sum.
theoremcard_active_slots
theorem card_active_slots (o : DeviceOp) (T : Nat) (h : o.end_t ≤ T) :
((Finset.range T).filter (fun t => o.activeAt t = true)).card = o.dur_tThe active time-slots of one op (whose window fits in `[0,T)`) number exactly its duration.
theoremop_slice
theorem op_slice (o : DeviceOp) (T : Nat) (h : o.end_t ≤ T) :
(∑ t ∈ Finset.range T, if o.activeAt t then o.footprint.length else 0) = opWork oThe per-op slice of spacetime equals its workload (footprint × duration), when it fits.
theoremspacetimeUsed_eq_workload
theorem spacetimeUsed_eq_workload (sched : DSchedule) (T : Nat)
(hfit : ∀ o ∈ sched, o.end_t ≤ T) :
spacetimeUsed sched T = workload sched*Fubini**: spacetime consumed = total workload, when every op fits in `[0,T)`.
theoremspacetimeUsed_le
theorem spacetimeUsed_le (sched : DSchedule) (T Q : Nat)
(hcap : ∀ t ∈ Finset.range T, activeFootprintSize sched t ≤ Q) :
spacetimeUsed sched T ≤ Q * TSpacetime consumed ≤ `Q · T` when capacity `Q` holds at every instant in `[0,T)`.
theoremworkload_le
theorem workload_le (sched : DSchedule) (T Q : Nat)
(hfit : ∀ o ∈ sched, o.end_t ≤ T)
(hcap : ∀ t ∈ Finset.range T, activeFootprintSize sched t ≤ Q) :
workload sched ≤ Q * T*★ Packing bound ★** — total reserved footprint-time ≤ device spacetime `Q · T`.
theoremworkload_ge_of_uniform
theorem workload_ge_of_uniform (sched : DSchedule) (fq prod : Nat)
(hf : ∀ o ∈ sched, fq ≤ o.footprint.length) (hd : ∀ o ∈ sched, prod ≤ o.dur_t) :
sched.length * (fq * prod) ≤ workload schedWorkload lower bound: ops each with footprint ≥ `fq` and duration ≥ `prod` reserve
`≥ (#ops) · fq · prod`.
theoremmagic_spacetime_floor
theorem magic_spacetime_floor (sched : DSchedule) (T Q fq prod : Nat)
(hfit : ∀ o ∈ sched, o.end_t ≤ T)
(hcap : ∀ t ∈ Finset.range T, activeFootprintSize sched t ≤ Q)
(hf : ∀ o ∈ sched, fq ≤ o.footprint.length) (hd : ∀ o ∈ sched, prod ≤ o.dur_t) :
sched.length * (fq * prod) ≤ Q * T*★ MAGIC-STATE SPACETIME FLOOR ★** — for ANY schedule producing magic states (each reserving
≥ `fq` factory qubits for ≥ `prod` time), conflict/capacity-bounded by `Q` over horizon `T`, the
device spacetime obeys `(#magic) · fq · prod ≤ Q · T`. No scheduling cleverness can beat the
magic-production spacetime floor.
defrsa2048_toffoli_budget
def rsa2048_toffoli_budget : Nat
The verified windowed RSA-2048 Toffoli (= CCZ magic) budget (`RSA2048.magicBudget`) — the
single canonical constant the naive schedule, the lower bound, and the hardware-sensitivity
floors all denominate against.
defrsa2048_floor_qubit_us
def rsa2048_floor_qubit_us : Nat
The magic-state spacetime floor for windowed RSA-2048, in qubit·µs:
`K · fq · prod = 2 622 824 448 · 2565 · 12000` — denominated, by construction, against the
canonical Toffoli budget and CCZ factory spec (`Params.RSA2048`).
defrsa2048_floor_qubit_hours
def rsa2048_floor_qubit_hours : Nat
The floor in qubit·HOURS (÷ 3.6×10⁹ µs/h) ≈ `2.24×10⁷`.
theoremrsa2048_floor_value
theorem rsa2048_floor_value : rsa2048_floor_qubit_hours = 22425149
theoremrsa2048_floor_gaps
theorem rsa2048_floor_gaps :
7 * rsa2048_floor_qubit_hours ≤ 20000000 * 8
∧ 20000000 * 8 ≤ 8 * rsa2048_floor_qubit_hours
∧ 3773 * rsa2048_floor_qubit_hours ≤ 9636357 * 8782
∧ 9636357 * 8782 ≤ 3774 * rsa2048_floor_qubit_hours*The paper sits between 7× and 8× above the floor; the naive baseline between 3773× and 3774×.**
Comparison inputs: paper spacetime = `20 000 000` qubits × `8` h (the GE2021 headline); naive
baseline = `9 636 357` qubits × `8 782` h, both derived and proven in
`Audit/GidneyEkera2021/Verifier` (`naiveQubits_value`: 9 633 792 data qubits + one 2565-qubit
factory; `naiveWallclockHours_value`: 2 622 824 448 Toffolis × 12 054 µs serial ÷ 3.6×10⁹ µs/h).
The paper is near the magic-production limit (good engineering); the naive serial baseline is far
above it — all the slack is in serial magic production.
FormalRV.System.Checkers.FaultTolerantSchedule
FormalRV/System/Checkers/FaultTolerantSchedule.lean
FormalRV.System.FTSchedule — SYSTEM-LEVEL FAULT-TOLERANT SCHEDULING.
The four hardware concerns are syscalls — RequestMagicState (T-factory),
RequestFreshAncilla (ancilla), TransitQubit (routing), DecodeSyndrome
(classical decoding) — and the decidable bundle
`ScheduleInv.all_invariants_ok` (capacity, exclusivity, latency/speed,
decoder reaction, throughput) guarantees they are schedulable. `ft_ok`
combines that bundle with a schedule-level decoder budget and distance
adequacy (3·τ_s ≥ 2·d). A passing `FTSchedule` is fault-tolerant:
schedulable (invariants) + error-suppressed (distance); the syscalls are
NON-SEMANTIC (we verify the schedule satisfies invariants + FT, not what
each syscall computes — the logical-action semantics live in
`QEC/LatticeSurgery/SurgeryCorrect`). Resource count (magic states,
ancillas, decode rounds, routing moves, wallclock) follows from the
schedule. Merged-code distance d̃ ≥ d is the delimited external input.
## How the rungs map to the bundle
**capacity** (`capacity_in_arch_ok` ∧ `capacity_per_cycle_ok`) — every
claimed atom lies in a zone, and no zone is over-subscribed at any
begin-time. This is the ANCILLA / qubit-budget concern.
**exclusivity** (`exclusivity_ok`) — time-overlapping syscalls claim
disjoint atoms. This is the no-double-booking concern.
**latency / speed** (`latency_speed_ok`) — feedback (`PauliFrameUpdate`)
completes within one stabilizer cycle, and every `TransitQubit` respects
`duration · v_max ≥ distance`. This is the ROUTING + feedback concern.
**decoder reaction** (`decoder_react_ok arch.t_react_us`) — every
`DecodeSyndrome` completes within the architecture's reaction budget
(the qianxu within-cycle decoding claim). This is the
CLASSICAL-DECODING concern.
**throughput** (`window_throughput_ok`) — magic-state demand per window
≤ supply. This is the T-FACTORY concern.
**distance adequacy** (`3·τ_s ≥ 2·d`) — the error-suppression rung, the
cycle-count analogue of `SurgeryCorrect.SurgeryFaultTolerant`'s
`merged_dist ≥ data_code.d`. τ_s must be large enough (≥ ⌈2d/3⌉) to
balance space-like and time-like logical error.
## The two decoder budgets
`all_invariants_ok` checks `decoder_react_ok` against the ARCHITECTURE
field `arch.t_react_us`; `ft_ok` ALSO checks it against the independent
SCHEDULE-LEVEL field `FTSchedule.t_react_us`. The effective decoder
budget is the minimum of the two. The second conjunct is not redundant:
the budgets can differ, `ftSchedule_guarantee` exposes
`decoder_react_ok f.t_react_us` in its conclusion, and
`demoFT_slowDecoder` below fails ONLY the schedule-level budget (its
`arch.t_react_us = 10` check passes).
No Mathlib. Pure List / Bool / Nat + `decide`. No `sorry`, no `axiom`,
no `admit`.
structureFTSchedule
structure FTSchedule
A fault-tolerant schedule: a syscall schedule on an architecture, plus the
distance/τ_s adequacy data.
defFTSchedule.distance_adequate
def FTSchedule.distance_adequate (f : FTSchedule) : Bool
Distance adequacy: τ_s ≥ ⌈2d/3⌉, i.e. 3τ_s ≥ 2d (the SurgeryFaultTolerant
cycle condition that balances space-like and time-like logical error).
defFTSchedule.ft_ok
def FTSchedule.ft_ok (f : FTSchedule) : Bool
The full FT-schedule check: the bundle `all_invariants_ok` (capacity =
ancilla, exclusivity, latency/speed = routing, decoder reaction vs
`arch.t_react_us`, throughput = T-factory) AND the decoder reaction-time
bound against the schedule-level budget `f.t_react_us` (independent of
`arch.t_react_us` — see "The two decoder budgets" in the header) AND
distance adequacy. All four hardware concerns — T-factory, ancilla,
routing, decoding — plus error-suppression are thereby covered.
theoremftSchedule_guarantee
theorem ftSchedule_guarantee (f : FTSchedule) (h : f.ft_ok = true) :
all_invariants_ok f.arch f.sched f.window_us f.max_per_window f.distance_fn = true
∧ decoder_react_ok f.t_react_us f.sched = true
∧ 3 * f.tau_s ≥ 2 * f.code_distanceA passing FT-schedule satisfies BOTH the system invariants (it is
schedulable: no resource conflicts, magic demand ≤ supply, latency within
budget) AND distance adequacy (error suppression governed by the code
distance). The merged-code distance d̃ ≥ d is the delimited external input
(cf. SurgeryFaultTolerant); semantic correctness of the surgery operations
is the already-proven
SurgeryCorrect.surgery_implements_logical_measurement. The system syscalls
themselves are non-semantic — only their invariant satisfaction matters
here.
abbrevcountKind
abbrev countKind : (SysCallKind → Bool) → List SysCall → Nat
Count syscalls whose kind satisfies the predicate `p` — an alias for
THE canonical counter (`Resource/SysCallCount.countWhere`).
abbrevmagicStateCount
abbrev magicStateCount : List SysCall → Nat
Number of magic-state requests (canonical counter).
abbrevancillaCount
abbrev ancillaCount : List SysCall → Nat
Number of fresh-ancilla requests (canonical counter).
abbrevdecodeRounds
abbrev decodeRounds : List SysCall → Nat
Number of decoder rounds (canonical counter).
abbrevroutingMoves
abbrev routingMoves : List SysCall → Nat
Number of routing moves (canonical counter).
defwallclock_us
def wallclock_us (s : List SysCall) : Nat
Wallclock = latest end timestamp.
structureSystemBudget
structure SystemBudget
The system-level resource budget extracted from a schedule.
defFTSchedule.budget
def FTSchedule.budget (f : FTSchedule) : SystemBudget
The resource budget of an FT-schedule: counts of each expensive resource
plus the wallclock. The "resource count follows" deliverable: every figure
is read off the schedule, not asserted.
defdemoArch
def demoArch : ZonedArch
The worked-instance architecture: Data[0,10) Workspace[10,20)
Factory[20,30) Routing[30,40), one stabilizer cycle = 100 µs, transport
speed limit 5 µm/µs.
defdemoDist
def demoDist : Nat → Nat
Route distance function: every channel covers 30 µm.
defdemoSched
def demoSched : List SysCall
The worked-instance schedule (all four hardware concerns + a surgery
measurement + a two-qubit gate, on disjoint valid atoms).
defdemoFT
def demoFT : FTSchedule
The worked FT-schedule instance. τ_s = 6, d = 9 ⇒ 3·6 = 18 ≥ 2·9 = 18.
example(example)
example : demoFT.ft_ok = true
The worked instance IS fault-tolerant: all four system invariants hold and
distance adequacy holds.
example(example)
example : demoFT.budget =
{ magic_statesThe resource count follows from the schedule: one magic state, one ancilla,
one decode round, one routing move; wallclock 45 µs.
theoremdemoFT_guarantee
theorem demoFT_guarantee :
all_invariants_ok demoFT.arch demoFT.sched demoFT.window_us demoFT.max_per_window
demoFT.distance_fn = true
∧ decoder_react_ok demoFT.t_react_us demoFT.sched = true
∧ 3 * demoFT.tau_s ≥ 2 * demoFT.code_distanceThe decomposed guarantee for the worked instance.
defdemoSched_slowTransit
def demoSched_slowTransit : List SysCall
A schedule identical to `demoSched` except the routing transit is too fast:
duration 2 µs at v_max = 5 gives 2·5 = 10 < 30 = distance, so the speed
limit (the routing rung of `latency_speed_ok`) is violated. This is the
discriminating "routing/latency too fast" case the bundle catches.
defdemoFT_slowTransit
def demoFT_slowTransit : FTSchedule
Routing speed-limit violation ⇒ `ft_ok = false`.
example(example)
example : demoFT_slowTransit.ft_ok = false
defdemoFT_slowDecoder
def demoFT_slowDecoder : FTSchedule
Decoder too slow for the SCHEDULE-LEVEL budget: `t_react_us := 2` is below
the `DecodeSyndrome` latency (25 − 20 = 5), so the
`decoder_react_ok f.t_react_us` conjunct fails ⇒ `ft_ok = false`. The
architecture budget (`arch.t_react_us = 10`) still passes, so this test is
exactly why the schedule-level conjunct is not redundant.
example(example)
example : demoFT_slowDecoder.ft_ok = false
defdemoFT_lowTauS
def demoFT_lowTauS : FTSchedule
Distance-inadequate: τ_s too small for d ⟹ `ft_ok = false`.
3·1 = 3 < 2·11 = 22, so distance adequacy fails.
example(example)
example : demoFT_lowTauS.ft_ok = false
example(example)
example : demoFT_lowTauS.distance_adequate = false
For completeness: the distance-adequacy conjunct is exactly what fails in
`demoFT_lowTauS` (the system invariants on the unchanged schedule still
hold).
FormalRV.System.Checkers.SystemChecker
FormalRV/System/Checkers/SystemChecker.lean
FormalRV.System.SystemChecker — an honest review of
what the system-layer checker accepts vs what it SHOULD reject
under the paper's abstraction.
## Why this file exists
The framework's strengthened system-layer checker
(`all_invariants_with_factory_ports_ok` from
`LatticeSurgeryPPMContract.lean`) accepts a schedule iff:
capacity_in_arch_ok ∧
capacity_per_cycle_ok ∧
exclusivity_ok ∧
factory_exclusivity_ok ∧
feedback_latency_ok ∧
decoder_react_ok ∧
window_throughput_ok
Each conjunct is decidable on concrete schedules; the bundle
closes by `native_decide` on small schedules. This file
systematically probes the bundle for gaps between "passes the
checker" and "is a physically/scheduler-valid schedule under
the paper abstraction".
We construct TINY concrete schedules that pass the checker
but violate one or more intended invariants, and prove via
`native_decide` that the checker accepts them. Each
counterexample is paired with a documentation block stating
exactly which invariant the paper requires that the checker
does not currently enforce.
## Relation to the strengthened checkers
The strengthened checkers live in
`Invariants/SystemInvariantStrengthening`: its strict bundles
add `feedback_after_decode_ok` (closing §4) and
`ancilla_freshness_ok` (closing §6), and keep the remaining
gaps (§3, §5, §7, §8) as named TODO regressions. This file is
the counterexample corpus those bundles import; the acceptance
theorems below remain true of the BASE bundle probed here.
Counterexamples that the base bundle correctly rejects also
live here (positive controls).
No `sorry`, no custom `axiom`. Pure Bool/Nat, `native_decide`.
theoremintervals_overlap_touching_disjoint
theorem intervals_overlap_touching_disjoint :
intervals_overlap 0 1 1 2 = falsetheoremintervals_overlap_strictly_disjoint
theorem intervals_overlap_strictly_disjoint :
intervals_overlap 0 2 2 4 = falsetheoremintervals_overlap_proper_overlap
theorem intervals_overlap_proper_overlap :
intervals_overlap 0 2 1 3 = truetheoremintervals_overlap_contained
theorem intervals_overlap_contained :
intervals_overlap 0 10 3 7 = truetheoremintervals_overlap_symmetric
theorem intervals_overlap_symmetric :
intervals_overlap 1 3 0 2 = truetheoremconnEdges_single_row_three_entries
theorem connEdges_single_row_three_entries :
connEdges [[true, false, true, false, true]] = [(0, 0), (0, 2), (0, 4)]theoremconnEdges_three_rows_one_entry
theorem connEdges_three_rows_one_entry :
connEdges [[false, true], [false, false], [true, false]]
= [(0, 1), (2, 0)]theoremconnEdges_all_false_empty
theorem connEdges_all_false_empty :
connEdges [[false, false], [false, false]] = []theoremconnEdges_empty_matrix
theorem connEdges_empty_matrix :
connEdges ([] : BoolMat) = []deftopology_demo_target_mutated_gadget
def topology_demo_target_mutated_gadget : SurgeryGadget
A topology-schedulable gadget cloned from `topology_demo`
but with `target_pauli` mutated to a DIFFERENT (still
row-span-valid) Pauli. Even with the mutation, the
compiled SysCall stream is identical to `topology_demo`'s.
We pick the same row-span witness so the mutated gadget
still passes the kernel-condition check; this isolates the
target_pauli-vs-SysCall gap.
theoremtopology_demo_target_mutated_differs
theorem topology_demo_target_mutated_differs :
topology_demo_target_mutated_gadget.target_pauli
≠ topology_demo_gadget.target_pauliThe mutated gadget has a different `target_pauli`.
deftopology_demo_target_mutated
def topology_demo_target_mutated : TopologySchedulableSurgeryGadget
A wrapper around the mutated gadget with the SAME
scheduling spec as `topology_demo`.
theoremtopology_compiler_ignores_target_pauli
theorem topology_compiler_ignores_target_pauli :
compileTopologySurgeryToSysCalls topology_demo_target_mutated
= compileTopologySurgeryToSysCalls topology_demo*The target_pauli gap, proven**: two gadgets with
DIFFERENT target_pauli compile to the SAME SysCall stream.
The SysCall-layer checker cannot tell which logical Pauli
is being measured.
defdecoder_dependency_violator
def decoder_dependency_violator : List SysCall
A schedule with PauliFrameUpdate at t=0..1 BEFORE the
matching DecodeSyndrome at t=10..11. Physically the
feedback cannot fire before the decoder runs, but the
current checker is silent on this dependency.
theoremdecoder_dependency_violator_accepted
theorem decoder_dependency_violator_accepted :
all_invariants_with_factory_ports_ok
surgery_arch decoder_dependency_violator
10 1000 1000 = true*Accepted-invalid schedule**: PauliFrameUpdate fires
before the matching DecodeSyndrome, but the strengthened
bundle accepts it.
defrouting_lane_violator
def routing_lane_violator : List SysCall
Two simultaneous `Gate2q`s on endpoint-disjoint sites
(0↔100 and 1↔101), but a real architecture might route
both through the same intermediate qubit/coupler. The
checker cannot see the coupler conflict.
theoremrouting_lane_violator_accepted
theorem routing_lane_violator_accepted :
all_invariants_with_factory_ports_ok
surgery_arch routing_lane_violator
10 1000 1000 = true*Accepted-invalid schedule (in principle)**: the
routing-lane gap is purely about what `syscall_acts_on`
reports; the checker has no way to know coupler conflicts
exist.
deffreshness_use_before_reset
def freshness_use_before_reset : List SysCall
A schedule that uses ancilla site 100 in a `Gate2q` BEFORE
issuing any `RequestFreshAncilla`. The checker accepts.
Physically the ancilla is undefined.
theoremfreshness_use_before_reset_accepted
theorem freshness_use_before_reset_accepted :
all_invariants_with_factory_ports_ok
surgery_arch freshness_use_before_reset
10 1000 1000 = truedeffreshness_reuse_without_reset
def freshness_reuse_without_reset : List SysCall
A schedule that REUSES ancilla site 100 across two Gate2qs
WITHOUT a `RequestFreshAncilla` reset between them.
Physically the second Gate2q operates on the post-Measure
classical state of the ancilla, not a fresh zero state.
theoremfreshness_reuse_without_reset_accepted
theorem freshness_reuse_without_reset_accepted :
all_invariants_with_factory_ports_ok
surgery_arch freshness_reuse_without_reset
10 1000 1000 = truedefsite_id_conflation
def site_id_conflation : List SysCall
A schedule mixing `Gate2q` on qubit 203 and
`RequestMagicState` on factory zone 3 (which claims port
`200 + 3 = 203`). These should refer to different
resources, but both use the bare `Nat` 203. The checker
treats them as independent.
theoremsite_id_conflation_accepted
theorem site_id_conflation_accepted :
all_invariants_with_factory_ports_ok
surgery_arch site_id_conflation
10 1000 1000 = truedefmagic_no_startup_prefix
def magic_no_startup_prefix : List SysCall
A schedule demanding a magic state at t=0 with no
production prefix. Passes the window check (1 ≤ 1) but
violates the causal availability `available(0) = 0`.
theoremmagic_no_startup_prefix_accepted
theorem magic_no_startup_prefix_accepted :
all_invariants_with_factory_ports_ok
surgery_arch magic_no_startup_prefix
10 1000 1 = truedefpositive_ancilla_alias
def positive_ancilla_alias : List SysCall
Two `Gate2q`s overlapping in time on the SAME ancilla
site are REJECTED (standard exclusivity catches it).
theorempositive_ancilla_alias_rejected
theorem positive_ancilla_alias_rejected :
all_invariants_with_factory_ports_ok
surgery_arch positive_ancilla_alias
10 1000 1000 = falsedefpositive_factory_port_alias
def positive_factory_port_alias : List SysCall
Two overlapping `RequestMagicState`s on the SAME factory
zone (port aliasing) are REJECTED.
theorempositive_factory_port_alias_rejected
theorem positive_factory_port_alias_rejected :
all_invariants_with_factory_ports_ok
surgery_arch positive_factory_port_alias
10 1000 1000 = falsedefpositive_off_arch_claim
def positive_off_arch_claim : List SysCall
An off-architecture atom claim (site 500 with arch size
400) is REJECTED by `capacity_in_arch_ok`.
theorempositive_off_arch_claim_rejected
theorem positive_off_arch_claim_rejected :
all_invariants_with_factory_ports_ok
surgery_arch positive_off_arch_claim
10 1000 1000 = falsedefpositive_decoder_too_slow
def positive_decoder_too_slow : List SysCall
A `DecodeSyndrome` exceeding its react budget is REJECTED.
theorempositive_decoder_too_slow_rejected
theorem positive_decoder_too_slow_rejected :
all_invariants_with_factory_ports_ok
surgery_arch positive_decoder_too_slow
10 1000 1000 = falseFormalRV.System.Compile.LatticeSurgeryPPMContract
FormalRV/System/Compile/LatticeSurgeryPPMContract.lean
FormalRV.System.LatticeSurgeryPPMContract — umbrella module kept
for downstream importers (SurgeryGadgetToSysCalls, SystemChecker,
SystemInvariantStrengthening, LayeredArtifactInterface,
CompressedRepeatSoundness, Examples/AdderSystem, Example/Adder2EndToEnd).
The former 1300-line file was split by topic; this module re-exports
everything via transitive imports, and every declaration keeps its
original fully-qualified name in
`FormalRV.System.LatticeSurgeryPPMContract`:
`Core/ScheduleCombinators.lean` — generic SysCall schedule
combinators (wallclock, shift, seq/par composition).
`Compile/PPMScheduleContract.lean` — the durable contract:
`PPMScheduleCert` / `PPMScheduleCertWithFactoryPorts`,
`factory_exclusivity_ok`, the strengthened bundle
`all_invariants_with_factory_ports_ok` + paper aliases, the
validator, builder, and compose-existence theorems.
`Compile/PPMContractInstances.lean` — GE2021 / PPM-pair / 3-PPM
worked instances, counterexamples, and failure-isolation theorems.
(no documented top-level declarations)
FormalRV.System.Compile.PPMContractInstances
FormalRV/System/Compile/PPMContractInstances.lean
FormalRV.System.Compile.PPMContractInstances — worked instances and
decide-verified positive/negative examples for the PPM schedule
contract in `PPMScheduleContract.lean`:
The GE2021 16-SysCall PPM block packaged as `PPMScheduleCert` and
as the strengthened cert (reusing the existing GE2021PPMSysInv
theorems, no re-proof).
`ppm_block` and the PPM-pair / 3-PPM schedules (sequential,
parallel-distinct, parallel-alias) with invariant proofs and
failure-isolation theorems.
Isolated counterexamples: I1 capacity (atom outside zones), I3
feedback latency (PauliFrameUpdate > t_cycle), and the factory-port
conflict that standard `exclusivity_ok` misses but the strengthened
bundle catches (`magic_factory_*`).
§14: documented structural limitation — an isolated
`capacity_per_cycle` failure is unreachable while zone capacity is
derived from the atom range.
§22: the compositional principle — two individually valid certs do
NOT auto-compose; merged streams must be revalidated
(`validate_parallel_alias_false` is the counterexample).
Extracted verbatim from the former monolithic
`LatticeSurgeryPPMContract.lean` (§2–§5, §6 examples, §7, §8,
§12–§14, §18–§20, §21 applications, §22; the original §-numbering is
kept). Declarations stay in
`namespace FormalRV.System.LatticeSurgeryPPMContract` to preserve
fully-qualified names. All invariants decide/native_decide-closed;
wallclocks foldl-derived. No sorry, no custom axioms.
defge2021_ppm_schedule_cert
def ge2021_ppm_schedule_cert : PPMScheduleCert
The GE2021 16-SysCall PPM block as a `PPMScheduleCert`.
Every proof field is a thin reference to the corresponding
existing theorem in `GE2021PPMSysInv.lean`.
theoremge2021_ppm_schedule_cert_all_ok
theorem ge2021_ppm_schedule_cert_all_ok :
capacity_in_arch_ok ge2021_ppm_schedule_cert.arch
ge2021_ppm_schedule_cert.syscalls
&& capacity_per_cycle_ok ge2021_ppm_schedule_cert.arch
ge2021_ppm_schedule_cert.syscalls
&& exclusivity_ok ge2021_ppm_schedule_cert.syscalls
&& feedback_latency_ok ge2021_ppm_schedule_cert.arch.t_cycle_us
ge2021_ppm_schedule_cert.syscalls = true*Headline**: the GE2021 PPM block, viewed as a
`PPMScheduleCert`, satisfies the derived all-invariants
bundle. REUSES the existing 7 invariant theorems.
theoremge2021_ppm_schedule_cert_wallclock
theorem ge2021_ppm_schedule_cert_wallclock :
ge2021_ppm_schedule_cert.wallclock_us = 16*Sanity**: derived wallclock for the GE2021 PPM block as a
cert is 16 µs (matches existing `ppm_block_wallclock_value`).
defppm_pair_arch
def ppm_pair_arch : ZonedArch
defppm_block
def ppm_block (start_us data anc decoder_id : Nat) : List SysCall
One PPM measurement: RequestFreshAncilla + Gate2q + Measure +
DecodeSyndrome. Parametric in start time, data-qubit id, and
ancilla-qubit id.
defppm_pair_sequential_syscalls
def ppm_pair_sequential_syscalls : List SysCall
*Sequential pair**: PPM A in [0, 4), PPM B in [10, 14).
Both use ancilla 100 — no time overlap, so I2 passes.
theoremppm_pair_sequential_capacity_in_arch_ok
theorem ppm_pair_sequential_capacity_in_arch_ok :
capacity_in_arch_ok ppm_pair_arch ppm_pair_sequential_syscalls = truetheoremppm_pair_sequential_exclusivity_ok
theorem ppm_pair_sequential_exclusivity_ok :
exclusivity_ok ppm_pair_sequential_syscalls = truetheoremppm_pair_sequential_feedback_latency_ok
theorem ppm_pair_sequential_feedback_latency_ok :
feedback_latency_ok ppm_pair_arch.t_cycle_us ppm_pair_sequential_syscalls = truetheoremppm_pair_sequential_decoder_react_ok
theorem ppm_pair_sequential_decoder_react_ok :
decoder_react_ok 10 ppm_pair_sequential_syscalls = truetheoremppm_pair_sequential_throughput_ok
theorem ppm_pair_sequential_throughput_ok :
window_throughput_ok ppm_pair_sequential_syscalls 1000 1000 = truetheoremppm_pair_sequential_all_invariants_ok
theorem ppm_pair_sequential_all_invariants_ok :
all_invariants_ok ppm_pair_arch ppm_pair_sequential_syscalls 1000 1000
(fun _ => 0) = truedefppm_pair_parallel_distinct_syscalls
def ppm_pair_parallel_distinct_syscalls : List SysCall
*Parallel-distinct pair**: PPM A and PPM B run in the SAME
time window [0, 4), but use DISTINCT ancillas (100 and 101).
I2 passes because the only shared timing class is the
different Gate2q calls with disjoint atom claims.
theoremppm_pair_parallel_distinct_exclusivity_ok
theorem ppm_pair_parallel_distinct_exclusivity_ok :
exclusivity_ok ppm_pair_parallel_distinct_syscalls = truetheoremppm_pair_parallel_distinct_all_invariants_ok
theorem ppm_pair_parallel_distinct_all_invariants_ok :
all_invariants_ok ppm_pair_arch ppm_pair_parallel_distinct_syscalls 1000 1000
(fun _ => 0) = truedefppm_pair_parallel_alias_syscalls
def ppm_pair_parallel_alias_syscalls : List SysCall
*Parallel-aliasing pair (BAD)**: PPM A and PPM B both use
ancilla 100 in the SAME time window. Their Gate2qs both claim
atom 100 at [1, 2). I2 REJECTS.
theoremppm_pair_parallel_alias_exclusivity_fails
theorem ppm_pair_parallel_alias_exclusivity_fails :
exclusivity_ok ppm_pair_parallel_alias_syscalls = falsetheoremppm_pair_parallel_alias_fails_only_exclusivity
theorem ppm_pair_parallel_alias_fails_only_exclusivity :
capacity_in_arch_ok ppm_pair_arch ppm_pair_parallel_alias_syscalls = true
∧ feedback_latency_ok ppm_pair_arch.t_cycle_us
ppm_pair_parallel_alias_syscalls = true
∧ decoder_react_ok 10 ppm_pair_parallel_alias_syscalls = true
∧ window_throughput_ok ppm_pair_parallel_alias_syscalls 1000 1000 = true
∧ exclusivity_ok ppm_pair_parallel_alias_syscalls = falseFailure isolation: the aliasing pair fails ONLY I2. I1, I3,
I4 still pass. This is exactly what the paper claims I2
catches when L3 gadgets are scheduled in parallel.
defcapacity_bad_schedule
def capacity_bad_schedule : List SysCall
theoremcapacity_bad_oversubscription_fails
theorem capacity_bad_oversubscription_fails :
capacity_in_arch_ok ppm_pair_arch capacity_bad_schedule = falsetheoremcapacity_bad_fails_only_capacity
theorem capacity_bad_fails_only_capacity :
capacity_in_arch_ok ppm_pair_arch capacity_bad_schedule = false
∧ exclusivity_ok capacity_bad_schedule = true
∧ feedback_latency_ok ppm_pair_arch.t_cycle_us capacity_bad_schedule = true
∧ decoder_react_ok 10 capacity_bad_schedule = true
∧ window_throughput_ok capacity_bad_schedule 1000 1000 = truedeffeedback_bad_slow_schedule
def feedback_bad_slow_schedule : List SysCall
theoremfeedback_bad_latency_fails
theorem feedback_bad_latency_fails :
feedback_latency_ok ppm_pair_arch.t_cycle_us feedback_bad_slow_schedule = falsetheoremfeedback_bad_fails_only_feedback_latency
theorem feedback_bad_fails_only_feedback_latency :
capacity_in_arch_ok ppm_pair_arch feedback_bad_slow_schedule = true
∧ exclusivity_ok feedback_bad_slow_schedule = true
∧ decoder_react_ok 10 feedback_bad_slow_schedule = true
∧ window_throughput_ok feedback_bad_slow_schedule 1000 1000 = true
∧ feedback_latency_ok ppm_pair_arch.t_cycle_us feedback_bad_slow_schedule = falsedefmagic_factory_distinct_schedule
def magic_factory_distinct_schedule : List SysCall
POSITIVE: two `RequestMagicState` calls overlapping in time
but targeting DIFFERENT factory zones (3 and 4). Their
factory ports are distinct (203 vs 204). ACCEPTED.
theoremmagic_factory_distinct_ports_ok
theorem magic_factory_distinct_ports_ok :
factory_exclusivity_ok magic_factory_distinct_schedule = truedefmagic_factory_same_port_schedule
def magic_factory_same_port_schedule : List SysCall
NEGATIVE: two `RequestMagicState` calls overlapping in time
AND targeting the SAME factory zone (3). Both claim port 203
at the same instant. REJECTED.
theoremmagic_factory_same_port_fails
theorem magic_factory_same_port_fails :
factory_exclusivity_ok magic_factory_same_port_schedule = falsetheoremmagic_factory_same_port_passes_standard_exclusivity
theorem magic_factory_same_port_passes_standard_exclusivity :
exclusivity_ok magic_factory_same_port_schedule = trueThe same-port schedule's standard `exclusivity_ok` still
PASSES — confirming the gap that the strengthening closes.
`syscall_acts_on` returns `[]` for `RequestMagicState`, so
the standard check is vacuous.
defppm_pair_sequential_wallclock_us
def ppm_pair_sequential_wallclock_us : Nat
Sequential pair's wallclock = 14 µs (= max end_us of PPM B's
DecodeSyndrome at 14).
theoremppm_pair_sequential_wallclock_value
theorem ppm_pair_sequential_wallclock_value :
ppm_pair_sequential_wallclock_us = 14defppm_pair_parallel_distinct_wallclock_us
def ppm_pair_parallel_distinct_wallclock_us : Nat
Parallel-distinct pair's wallclock = 4 µs (both PPMs end at 4).
theoremppm_pair_parallel_distinct_wallclock_value
theorem ppm_pair_parallel_distinct_wallclock_value :
ppm_pair_parallel_distinct_wallclock_us = 4theoremexclusivity_with_factory_ports_detects_same_port
theorem exclusivity_with_factory_ports_detects_same_port :
exclusivity_with_factory_ports_ok magic_factory_same_port_schedule = falseThe same-port bad schedule fails the strengthened exclusivity
check.
theoremexclusivity_with_factory_ports_accepts_distinct_ports
theorem exclusivity_with_factory_ports_accepts_distinct_ports :
exclusivity_with_factory_ports_ok magic_factory_distinct_schedule = trueThe distinct-ports good schedule passes the strengthened
exclusivity check.
theoremge2021_ppm_block_factory_exclusivity_ok
theorem ge2021_ppm_block_factory_exclusivity_ok :
factory_exclusivity_ok ppm_block_syscalls = truedefge2021_ppm_schedule_cert_with_factory_ports
def ge2021_ppm_schedule_cert_with_factory_ports : PPMScheduleCertWithFactoryPorts
theoremge2021_ppm_schedule_cert_with_factory_ports_all_ok
theorem ge2021_ppm_schedule_cert_with_factory_ports_all_ok :
all_invariants_with_factory_ports_ok
ge2021_ppm_schedule_cert_with_factory_ports.arch
ge2021_ppm_schedule_cert_with_factory_ports.syscalls
ge2021_ppm_schedule_cert_with_factory_ports.t_react_us
ge2021_ppm_schedule_cert_with_factory_ports.window_us
ge2021_ppm_schedule_cert_with_factory_ports.max_per_window = trueThe GE2021 PPM block, packaged as the strengthened cert,
passes the strengthened all-invariants bundle.
theoremppm_pair_sequential_factory_exclusivity_ok
theorem ppm_pair_sequential_factory_exclusivity_ok :
factory_exclusivity_ok ppm_pair_sequential_syscalls = truetheoremppm_pair_sequential_all_invariants_with_factory_ports_ok
theorem ppm_pair_sequential_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch ppm_pair_sequential_syscalls 10 1000 1000 = truetheoremppm_pair_parallel_distinct_factory_exclusivity_ok
theorem ppm_pair_parallel_distinct_factory_exclusivity_ok :
factory_exclusivity_ok ppm_pair_parallel_distinct_syscalls = truetheoremppm_pair_parallel_distinct_all_invariants_with_factory_ports_ok
theorem ppm_pair_parallel_distinct_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch ppm_pair_parallel_distinct_syscalls 10 1000 1000 = truedefmagic_factory_arch
def magic_factory_arch : ZonedArch
Architecture extending `magic_demo_arch` with the same
structure as in `SystemLevelMagicSchedule`, used here to
evaluate the strengthened bundle on the same-port bad
schedule.
theoremmagic_factory_same_port_fails_strengthened_bundle
theorem magic_factory_same_port_fails_strengthened_bundle :
all_invariants_with_factory_ports_ok
magic_factory_arch magic_factory_same_port_schedule
10 15 2 = false*Strengthened-bundle headline**: the same-port bad schedule
is REJECTED by the strengthened all-invariants bundle.
We use `max_per_window = 2` (not 1) here so that the schedule
DOES satisfy throughput — the rejection is then SPECIFICALLY
from `factory_exclusivity_ok`. With `max_per_window = 1` the
same schedule would also fail throughput, masking the
factory-exclusivity isolation result below.
theoremmagic_factory_same_port_fails_only_factory_exclusivity
theorem magic_factory_same_port_fails_only_factory_exclusivity :
capacity_in_arch_ok magic_factory_arch magic_factory_same_port_schedule = true
∧ capacity_per_cycle_ok magic_factory_arch magic_factory_same_port_schedule = true
∧ exclusivity_ok magic_factory_same_port_schedule = true
∧ factory_exclusivity_ok magic_factory_same_port_schedule = false
∧ feedback_latency_ok magic_factory_arch.t_cycle_us
magic_factory_same_port_schedule = true
∧ decoder_react_ok 10 magic_factory_same_port_schedule = true
∧ window_throughput_ok magic_factory_same_port_schedule 15 2 = true*Failure isolation**: the same-port conflict fails ONLY the
factory-exclusivity check. All other six constituent
checks (capacity_in_arch + capacity_per_cycle + exclusivity +
feedback_latency + decoder_react + throughput) PASS at
`(window_us = 15, max_per_window = 2)`. This is the
paper-facing result: the strengthened bundle catches a
conflict that the standard six checks all miss.
theoremmagic_factory_same_port_passes_standard_bundle
theorem magic_factory_same_port_passes_standard_bundle :
all_invariants_ok magic_factory_arch magic_factory_same_port_schedule
15 2 (fun _ => 0) = trueHeadline-comparison theorem: standard `all_invariants_ok` also
misses the same-port conflict at `(window_us = 15,
max_per_window = 2)`.
theoremmagic_factory_same_port_standard_vs_strengthened
theorem magic_factory_same_port_standard_vs_strengthened :
all_invariants_ok magic_factory_arch magic_factory_same_port_schedule
15 2 (fun _ => 0) = true
∧ all_invariants_with_factory_ports_ok
magic_factory_arch magic_factory_same_port_schedule
10 15 2 = falseThe standard bundle passes; the strengthened bundle fails.
defper_cycle_three_active_schedule
def per_cycle_three_active_schedule : List SysCall
A would-be per-cycle oversubscription witness: three Gate2qs
in [0, 1) each claiming a distinct atom in the Data zone.
The Data zone has range [0, 100) — capacity 100. Three
distinct atoms is well within capacity. Demonstrates that
distinct-atom claims cannot oversubscribe a zone whose
capacity equals its range size.
theoremper_cycle_three_active_capacity_passes
theorem per_cycle_three_active_capacity_passes :
capacity_per_cycle_ok ppm_pair_arch per_cycle_three_active_schedule = trueConfirms the structural argument: per-cycle capacity always
passes when distinct atoms are used inside an
atom-range-equals-capacity zone.
theoremper_cycle_three_active_exclusivity_passes
theorem per_cycle_three_active_exclusivity_passes :
exclusivity_ok per_cycle_three_active_schedule = trueAnd exclusivity ALSO passes (distinct atoms, but overlapping
times) — confirming that an isolated `capacity_per_cycle`
failure is unreachable in the current model.
theoremseq_ppm_pair_cert_exists
theorem seq_ppm_pair_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ppm_pair_arch
∧ cert.syscalls = ppm_pair_sequential_syscalls
∧ cert.wallclock_us = scheduleWallclockUs ppm_pair_sequential_syscalls*Sequential PPM-pair cert exists**: the existing
`ppm_pair_sequential_syscalls` produces a cert under the
`ppm_pair_arch` + standard parameters.
theorempar_ppm_pair_distinct_cert_exists
theorem par_ppm_pair_distinct_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ppm_pair_arch
∧ cert.syscalls = ppm_pair_parallel_distinct_syscalls
∧ cert.wallclock_us = scheduleWallclockUs ppm_pair_parallel_distinct_syscalls*Parallel-distinct PPM-pair cert exists**.
theoremvalidate_parallel_alias_false
theorem validate_parallel_alias_false :
validateScheduleWithFactoryPorts
ppm_pair_arch ppm_pair_parallel_alias_syscalls 10 1000 1000 = false*Parallel-aliasing PPM-pair is REJECTED at the validator
level**: no strengthened cert can be constructed because the
merged schedule fails `exclusivity_ok`.
defppm_compose_A
def ppm_compose_A : List SysCall
Block A: a PPM block at `start_us = 0` on data 0, ancilla 100.
defppm_compose_B_same_anc
def ppm_compose_B_same_anc : List SysCall
Block B: a PPM block at `start_us = 0` on data 50, ancilla 100.
Same ancilla as A — for sequential composition this is fine
(B gets shifted past A's wallclock); for parallel composition
it causes aliasing.
defppm_compose_B_distinct_anc
def ppm_compose_B_distinct_anc : List SysCall
Block B with a DISTINCT ancilla (101).
defppm_compose_C_distinct_anc
def ppm_compose_C_distinct_anc : List SysCall
Block C with a third distinct ancilla (102).
defseq_compose_AB
def seq_compose_AB : List SysCall
*Sequential composition of A then B (same ancilla, but
shifted so B starts at wallclock(A) = 4)**: PASSES the
strengthened bundle.
theoremseq_compose_AB_all_invariants_with_factory_ports_ok
theorem seq_compose_AB_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch seq_compose_AB 10 1000 1000 = truedefpar_compose_AB_distinct
def par_compose_AB_distinct : List SysCall
*Parallel composition of A and B (distinct ancillas)**:
PASSES.
theorempar_compose_AB_distinct_all_invariants_with_factory_ports_ok
theorem par_compose_AB_distinct_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch par_compose_AB_distinct 10 1000 1000 = truedefpar_compose_AB_alias
def par_compose_AB_alias : List SysCall
*Parallel composition of A and B (same ancilla)**: REJECTED
by exclusivity, since both Gate2qs at [1, 2) claim site 100.
(Legacy `atom` is read as `site` in platform-neutral terms;
see `SurgeryGadgetToSysCalls.lean` §0.)
theorempar_compose_AB_alias_rejected
theorem par_compose_AB_alias_rejected :
validateScheduleWithFactoryPorts
ppm_pair_arch par_compose_AB_alias 10 1000 1000 = falsedefppm_triple_sequential_syscalls
def ppm_triple_sequential_syscalls : List SysCall
*3-PPM sequential**: A then B then C, each shifted past the
previous's wallclock. All distinct data qubits and ancillas
(the alias-safety hypothesis for sequential isn't required
here since the times are disjoint anyway).
theoremppm_triple_sequential_all_invariants_with_factory_ports_ok
theorem ppm_triple_sequential_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch ppm_triple_sequential_syscalls 10 1000 1000 = truedefppm_triple_parallel_distinct_syscalls
def ppm_triple_parallel_distinct_syscalls : List SysCall
*3-PPM parallel-distinct**: A, B, C all at t=0..4 using
distinct ancillas 100, 101, 102.
theoremppm_triple_parallel_distinct_all_invariants_with_factory_ports_ok
theorem ppm_triple_parallel_distinct_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok
ppm_pair_arch ppm_triple_parallel_distinct_syscalls 10 1000 1000 = truedefppm_triple_ctx
def ppm_triple_ctx : PPMComposeContext
Worked applications of the compose-many theorems on the 3-PPM
schedules from §20.
theoremppm_triple_sequential_cert_exists
theorem ppm_triple_sequential_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ppm_triple_ctx.arch
∧ cert.syscalls = ppm_triple_sequential_syscallstheoremppm_triple_parallel_distinct_cert_exists
theorem ppm_triple_parallel_distinct_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ppm_triple_ctx.arch
∧ cert.syscalls = ppm_triple_parallel_distinct_syscallsFormalRV.System.Compile.PPMScheduleContract
FormalRV/System/Compile/PPMScheduleContract.lean
FormalRV.System.Compile.PPMScheduleContract — the durable L3
lattice-surgery / PPM schedule contract.
`PPMScheduleCert` — architecture + SysCall stream + decidable proofs
of I1 (capacity), I2 (exclusivity), I3 (feedback latency + decoder
reaction), I4 (throughput), with foldl-derived wallclock.
`syscall_factory_claims` / `factory_exclusivity_ok` — the local
factory-port claim model (RequestMagicState zone_id claims port
200 + zone_id); a scheduler-level claim model, not physical truth.
`all_invariants_with_factory_ports_ok` — the OFFICIAL strengthened
bundle (adds factory-port exclusivity and decoder reaction; omits
speed_limit for transit-free schedules), with paper aliases
`paper_I1_ok`..`paper_I4_ok` and the bundle-equivalence theorem.
`PPMScheduleCertWithFactoryPorts` — the strengthened sibling cert
and its bundle theorem.
Composition layer: `PPMComposeContext`,
`validateScheduleWithFactoryPorts`, the 7-proof builder
`mkPPMScheduleCertWithFactoryPorts`, the bundle-to-cert existence
theorem, and the seq/par compose-many existence theorems
(revalidation principle: merged streams are re-checked decidably).
Extracted verbatim from the former monolithic
`LatticeSurgeryPPMContract.lean` (§1, §6 defs, §10, §11, §17, §21
generic theorems; the original §-numbering is kept). Declarations
stay in `namespace FormalRV.System.LatticeSurgeryPPMContract` to
preserve fully-qualified names. Worked instances and counterexamples
live in `PPMContractInstances.lean`. No Mathlib; Bool/Nat/List only.
structurePPMScheduleCert
structure PPMScheduleCert
A reusable certificate for one L3 lattice-surgery / PPM
gadget compiled into a SysCall stream.
The architecture, syscalls, and the three constants
(`t_react_us`, `window_us`, `max_per_window`) define the
verification context. The remaining fields are PROOFS that
the four system-level invariants hold:
capacity_in_arch (I1, every claimed atom in some zone)
capacity_per_cycle (I1, per-zone per-cycle aggregate)
exclusivity (I2)
feedback_latency (I3, PauliFrameUpdate ≤ t_cycle)
decoder_react (I3, DecodeSyndrome ≤ t_react)
throughput (I4, per-window magicReq count ≤ max_per_window)
The wallclock proof field makes the anti-spreadsheet property
explicit: `wallclock_us` is a `foldl` over the SysCall list,
not a typed-in Nat.
theoremall_invariants_ok_of_cert
theorem all_invariants_ok_of_cert (c : PPMScheduleCert) :
capacity_in_arch_ok c.arch c.syscalls
&& capacity_per_cycle_ok c.arch c.syscalls
&& exclusivity_ok c.syscalls
&& feedback_latency_ok c.arch.t_cycle_us c.syscalls = trueDerived bundle: every cert satisfies `all_invariants_ok` from
`ScheduleInvariantsExplicit` (sans the not-yet-included
decoder-react check, which is carried separately as
`decoder_react`).
The framework's `all_invariants_ok` uses
`latency_speed_ok = feedback_latency_ok && speed_limit_ok`;
we discharge the `feedback_latency_ok` half from
`feedback_latency`, and the `speed_limit_ok` half is vacuous
for the no-transit case (the cert's distance function is
`fun _ => 0`, so every transit's `distance / v_max` budget is
0, trivially satisfied).
defsyscall_factory_claims
def syscall_factory_claims : SysCall → List Nat
| sc => match sc.kind with
| .RequestMagicState zone_id => [200 + zone_id]
| _ => []Local: what factory port (if any) a SysCall claims. Currently
only `RequestMagicState zone_id` claims port `200 + zone_id`.
deffactory_exclusivity_ok
def factory_exclusivity_ok (sched : List SysCall) : Bool
Local: factory-port exclusivity. Pairwise check that any two
SysCalls overlapping in time have DISJOINT factory-port
claims. Mirrors the framework's `exclusivity_ok` shape but on
`syscall_factory_claims` instead of `syscall_acts_on`.
defexclusivity_with_factory_ports_ok
def exclusivity_with_factory_ports_ok (sched : List SysCall) : Bool
Strengthened exclusivity check: standard `exclusivity_ok` AND
factory-port exclusivity.
defall_invariants_with_factory_ports_ok
def all_invariants_with_factory_ports_ok
(arch : ZonedArch) (sched : List SysCall)
(t_react_us window_us max_per_window : Nat) : BoolThe OFFICIAL strengthened system-layer invariant bundle:
capacity (I1) + exclusivity (I2) + factory-port exclusivity
(I2*) + feedback latency (I3) + decoder reaction (I3) +
throughput (I4).
Comparison with the framework's
`ScheduleInv.all_invariants_ok`:
That one BUNDLES `feedback_latency_ok` + `speed_limit_ok`
as `latency_speed_ok` and OMITS `decoder_react_ok`.
This one EXPLICITLY includes `decoder_react_ok` and the
new `factory_exclusivity_ok`.
`speed_limit_ok` is omitted because the relevant
schedules have no `TransitQubit` calls.
defpaper_I1_ok
def paper_I1_ok (arch : ZonedArch) (sched : List SysCall) : Bool
*Paper I1**: capacity = `capacity_in_arch_ok` ∧ `capacity_per_cycle_ok`.
defpaper_I2_strengthened_ok
def paper_I2_strengthened_ok (sched : List SysCall) : Bool
*Paper I2 (strengthened)**: exclusivity = `exclusivity_ok`
∧ `factory_exclusivity_ok`. Standard `exclusivity_ok` alone
misses factory-port conflicts.
defpaper_I3_ok
def paper_I3_ok (arch : ZonedArch) (sched : List SysCall) (t_react_us : Nat) : Bool
*Paper I3**: latency = `feedback_latency_ok` ∧ `decoder_react_ok`.
defpaper_I4_ok
def paper_I4_ok (sched : List SysCall) (window_us max_per_window : Nat) : Bool
*Paper I4**: throughput = `window_throughput_ok`.
theoremall_invariants_with_factory_ports_eq_paper_invariants
theorem all_invariants_with_factory_ports_eq_paper_invariants
(arch : ZonedArch) (sched : List SysCall)
(t_react_us window_us max_per_window : Nat) :
all_invariants_with_factory_ports_ok arch sched
t_react_us window_us max_per_window
= (paper_I1_ok arch sched
&& paper_I2_strengthened_ok sched
&& paper_I3_ok arch sched t_react_us
&& paper_I4_ok sched window_us max_per_window)Bundle equivalence: `all_invariants_with_factory_ports_ok` is
EXACTLY the conjunction `paper_I1 ∧ paper_I2_strengthened ∧
paper_I3 ∧ paper_I4`. By `rfl` since both sides unfold to the
same chain of `&&`.
structurePPMScheduleCertWithFactoryPorts
structure PPMScheduleCertWithFactoryPorts
Strengthened sibling cert: same shape as `PPMScheduleCert`
but with an EXTRA proof field for `factory_exclusivity_ok`.
theoremall_invariants_ok_of_cert
theorem all_invariants_ok_of_cert (c : PPMScheduleCertWithFactoryPorts) :
all_invariants_with_factory_ports_ok
c.arch c.syscalls c.t_react_us c.window_us c.max_per_window = trueBundle theorem: every strengthened cert satisfies the
strengthened all-invariants bundle.
structurePPMComposeContext
structure PPMComposeContext
Verification context for composition. Fixes the architecture
and the three timing/throughput parameters under which the
merged schedule will be validated.
defvalidateScheduleWithFactoryPorts
def validateScheduleWithFactoryPorts
(arch : ZonedArch) (syscalls : List SysCall)
(t_react_us window_us max_per_window : Nat) : BoolThe generic strengthened-bundle validator.
defPPMComposeContext.validate
def PPMComposeContext.validate
(ctx : PPMComposeContext) (syscalls : List SysCall) : BoolValidate a merged schedule under a `PPMComposeContext`.
defmkPPMScheduleCertWithFactoryPorts
def mkPPMScheduleCertWithFactoryPorts
(arch : ZonedArch) (syscalls : List SysCall)
(t_react_us window_us max_per_window : Nat)
(h_cap : capacity_in_arch_ok arch syscalls = true)
(h_per_cycle : capacity_per_cycle_ok arch syscalls = true)
(h_excl : exclusivity_ok syscalls = true)
(h_fact : factory_exclusivity_ok syscalls = true)
(h_fbk : feedback_latency_ok arch.t_cycle_us syscalls = true)
(h_decode : decoder_react_ok t_react_us syscalls = true)
(h_throt : window_throughput_ok syscalls window_us max_per_window = true) :
PPMScheduleCertWithFactoryPortsA non-dependent direct-construction builder taking the 7
invariant proofs separately. Used internally by the
bundle-based existence theorem below.
theoremmkPPMScheduleCertWithFactoryPorts_of_valid
theorem mkPPMScheduleCertWithFactoryPorts_of_valid
(arch : ZonedArch) (syscalls : List SysCall)
(t_react_us window_us max_per_window : Nat)
(h : all_invariants_with_factory_ports_ok arch syscalls
t_react_us window_us max_per_window = true) :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = arch
∧ cert.syscalls = syscalls
∧ cert.t_react_us = t_react_us
∧ cert.window_us = window_us
∧ cert.max_per_window = max_per_window
∧ cert.wallclock_us = scheduleWallclockUs syscalls*Existence theorem (cert from a valid bundle)**: whenever
`all_invariants_with_factory_ports_ok` holds on a schedule,
a strengthened cert exists with matching fields and a derived
wallclock. Unpacks the bundle into its 7 component facts
and feeds them to the builder.
theoremcomposeSeqSchedulesWithFactoryPorts_of_valid
theorem composeSeqSchedulesWithFactoryPorts_of_valid
(ctx : PPMComposeContext) (blocks : List (List SysCall))
(h : all_invariants_with_factory_ports_ok ctx.arch
(seqManySchedules blocks)
ctx.t_react_us ctx.window_us ctx.max_per_window = true) :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ctx.arch
∧ cert.syscalls = seqManySchedules blocks
∧ cert.wallclock_us = scheduleWallclockUs (seqManySchedules blocks)*Compose-many existence theorem**: given a list of SysCall
sub-streams (one per PPM gadget), if the SEQUENTIALLY merged
stream passes the strengthened bundle under the given context,
then a strengthened cert exists for the merged stream.
theoremcomposeParSchedulesWithFactoryPorts_of_valid
theorem composeParSchedulesWithFactoryPorts_of_valid
(ctx : PPMComposeContext) (blocks : List (List SysCall))
(h : all_invariants_with_factory_ports_ok ctx.arch
(parManySchedules blocks)
ctx.t_react_us ctx.window_us ctx.max_per_window = true) :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ctx.arch
∧ cert.syscalls = parManySchedules blocks
∧ cert.wallclock_us = scheduleWallclockUs (parManySchedules blocks)*Compose-many existence theorem (parallel variant)**.
FormalRV.System.Compile.QECScheduleToSystem
FormalRV/System/Compile/QECScheduleToSystem.lean
FormalRV.System.Compile.QECScheduleToSystem — **W2: the QEC→System driver.**
The pipeline is
Shor @ PPM ──W1──► QEC layer ──W2──► System layer
(`Schedule = List SurgeryGadget`:
merges / CCZ injection, SEMANTICS)
This module is W2: an EXECUTABLE whole-program compiler from a QEC-layer
surgery program to the system-level `List SysCall` that the decidable
invariant bundle (`HardwareCatalog.checkScheduleOn`) and the FTQ-VM check.
It replaces the removed legacy artifacts (hand-written `shorSched`,
replicate-one-gadget `shorSchedule`): every SysCall here is DERIVED from
the QEC gadgets' connection matrices, never typed in.
Design points (each fixing an audited gap):
**Whole programs, not single gadgets** — `compileQECProgram` drives a
`List QECEvent` with a running clock and a running decoder-round
counter; gadgets are HETEROGENEOUS (any mix of merges and magic
injections).
**Globally unique decode ids** — round ids are strictly consecutive
across the whole program (`decodeIds_eq_range'`), so every
`PauliFrameUpdate` matches EXACTLY ONE `DecodeSyndrome` (no
stale-syndrome aliasing; the Lean existential check and the FTQ-VM
token FIFO agree by construction).
**Explicit-qubit discipline** — every ancilla site a round touches is
explicitly requested (`RequestFreshAncilla site`) and re-requested
after its dirtying measurement, satisfying `ancilla_freshness_ok`.
**Magic binding** — a `teleportCCX` injection is one
`RequestMagicState` followed by its three merge gadgets
(`QECEvent.cczInjection`, anchored to the QEC layer's
`cczInjectionSchedule`).
**Resource counting by recursion** — `programSyscallCount` /
`programRounds` give closed counts proven equal to the compiled
output's, the seed of symbolic resource upper bounds at this layer.
inductiveQECEvent
inductive QECEvent
abbrevQECProgram
abbrev QECProgram
defofSchedule
def ofSchedule (s : List SurgeryGadget) : QECProgram
Embed a plain QEC `Schedule` (no magic).
defQECEvent.cczInjection
def QECEvent.cczInjection (factory : Nat) (mA mB mC : SurgeryGadget) : QECEvent
A `teleportCCX` injection event, anchored to the QEC layer's
`cczInjectionSchedule` (3 merges + exactly 1 magic state).
defQECEvent.wf
def QECEvent.wf : QECEvent → Bool | .surgery g => decide (1 ≤ g.tau_s) | .magicSurgery _ gs => gs.all (fun g => decide (1 ≤ g.tau_s))
Every gadget must run ≥ 1 syndrome round (a 0-round gadget would emit
a frame update with no decode to match).
defprogramWf
def programWf (p : QECProgram) : Bool
structureSurgeryLayout
structure SurgeryLayout
defgateCount
def gateCount (g : SurgeryGadget) : Nat
Gate2q count of one round (true entries of both connection matrices).
defroundLen
def roundLen (g : SurgeryGadget) : Nat
SysCalls per round: `a` requests + `G` gates + `a` measures + 1 decode.
defgadgetLen
def gadgetLen (g : SurgeryGadget) : Nat
SysCalls per gadget: `tau_s` rounds + the final frame update.
defemitRound
def emitRound (L : SurgeryLayout) (g : SurgeryGadget)
(t0 rid : Nat) : List SysCalldefemitGadget
def emitGadget (L : SurgeryLayout) (g : SurgeryGadget)
(t base : Nat) : List SysCallCompile one gadget at start time `t`, decoder base `base`: `tau_s`
rounds with CONSECUTIVE decode ids, then one frame update keyed to
the gadget's base round.
defcompileGadgets
def compileGadgets (L : SurgeryLayout) :
List SurgeryGadget → Nat → Nat → List SysCall
| [], _, _ => []
| g :: gs, t, base =>
emitGadget L g t base
++ compileGadgets L gs (t + gadgetLen g) (base + g.tau_s)Compile a gadget list sequentially, threading (clock, next round id).
defgadgetsRounds
def gadgetsRounds (gs : List SurgeryGadget) : Nat
Rounds consumed by a gadget list.
defgadgetsDuration
def gadgetsDuration (gs : List SurgeryGadget) : Nat
Duration (µs) of a compiled gadget list.
defeventRounds
def eventRounds : QECEvent → Nat | .surgery g => g.tau_s | .magicSurgery _ gs => gadgetsRounds gs
defeventDuration
def eventDuration : QECEvent → Nat | .surgery g => gadgetLen g | .magicSurgery _ gs => 1 + gadgetsDuration gs
defeventSyscallCount
def eventSyscallCount : QECEvent → Nat | .surgery g => gadgetLen g | .magicSurgery _ gs => 1 + (gs.map gadgetLen).sum
defcompileEvent
def compileEvent (L : SurgeryLayout) (t base : Nat) : QECEvent → List SysCall
| .surgery g => emitGadget L g t base
| .magicSurgery factory gs =>
{ kindCompile one event at (t, base).
defcompileEvents
def compileEvents (L : SurgeryLayout) :
QECProgram → Nat → Nat → List SysCall
| [], _, _ => []
| e :: es, t, base =>
compileEvent L t base e
++ compileEvents L es (t + eventDuration e) (base + eventRounds e)*The W2 driver**: compile a heterogeneous QEC program to one
system-level SysCall schedule, threading the clock and the global
decoder-round counter.
defcompileQECProgram
def compileQECProgram (L : SurgeryLayout) (p : QECProgram)
(t0 : NatdefprogramSyscallCount
def programSyscallCount (p : QECProgram) : Nat
Closed-form SysCall count of a compiled program (recursive — no
expansion needed to know the size).
defprogramRounds
def programRounds (p : QECProgram) : Nat
Closed-form total round count.
defdecode_ids_unique_ok
def decode_ids_unique_ok (sched : List SysCall) : Bool
Every decode id is distinct AND every frame update has a matching
decode — together with the bundle's `feedback_after_decode_ok` this
upgrades "some same-id decode ended earlier" to "EXACTLY ONE matching
decode exists" (no stale-syndrome aliasing). Built ON the canonical
counters (a verifier USING the counting system, never redefining it).
theoremrange'_append_one
private theorem range'_append_one (s m n : Nat) :
List.range' s m ++ List.range' (s + m) n = List.range' s (m + n)`range'` glue (step 1), proven directly to avoid step-argument
normalization games.
theoremdecodeIds_emitRound
theorem decodeIds_emitRound (L : SurgeryLayout) (g : SurgeryGadget)
(t0 rid : Nat) : decodeIds (emitRound L g t0 rid) = [rid]One round contributes exactly its decode id.
theoremdecodeIds_emitGadget
theorem decodeIds_emitGadget (L : SurgeryLayout) (g : SurgeryGadget)
(t base : Nat) :
decodeIds (emitGadget L g t base) = List.range' base g.tau_sA gadget's decode ids are the consecutive block `[base, base+tau_s)`.
theoremdecodeIds_compileGadgets
theorem decodeIds_compileGadgets (L : SurgeryLayout) :
∀ (gs : List SurgeryGadget) (t base : Nat),
decodeIds (compileGadgets L gs t base)
= List.range' base (gadgetsRounds gs)
| [], _, _ => by simp [compileGadgets, decodeIds, gadgetsRounds]
| g :: gs, t, base =>*Compiled programs have globally consecutive decode ids** —
`decodeIds (compileEvents L p t base) = [base, base + programRounds p)`.
Uniqueness (`Nodup`) is immediate from `List.nodup_range'`.
theoremdecodeIds_compileEvent
theorem decodeIds_compileEvent (L : SurgeryLayout) (t base : Nat)
(e : QECEvent) :
decodeIds (compileEvent L t base e) = List.range' base (eventRounds e)theoremdecodeIds_compileEvents
theorem decodeIds_compileEvents (L : SurgeryLayout) :
∀ (p : QECProgram) (t base : Nat),
decodeIds (compileEvents L p t base)
= List.range' base (programRounds p)
| [], _, _ => by simp [compileEvents, decodeIds, programRounds]
| e :: es, t, base =>theoremcompileQECProgram_decodeIds_nodup
theorem compileQECProgram_decodeIds_nodup
(L : SurgeryLayout) (p : QECProgram) (t0 round0 : Nat) :
(decodeIds (compileQECProgram L p t0 round0)).Nodup*The aliasing gap is closed for compiled programs** (parametric, any
layout, any program): all decode ids are distinct.
theorememitRound_length
theorem emitRound_length (L : SurgeryLayout) (g : SurgeryGadget)
(t0 rid : Nat) : (emitRound L g t0 rid).length = roundLen gtheorememitGadget_length
theorem emitGadget_length (L : SurgeryLayout) (g : SurgeryGadget)
(t base : Nat) : (emitGadget L g t base).length = gadgetLen gtheoremcompileGadgets_length
theorem compileGadgets_length (L : SurgeryLayout) :
∀ (gs : List SurgeryGadget) (t base : Nat),
(compileGadgets L gs t base).length = (gs.map gadgetLen).sum
| [], _, _ => rfl
| g :: gs, t, base =>theoremcompileQECProgram_length
theorem compileQECProgram_length (L : SurgeryLayout) :
∀ (p : QECProgram) (t0 round0 : Nat),
(compileQECProgram L p t0 round0).length = programSyscallCount p
| [], _, _ => rfl
| e :: es, t, base =>*count = expansion** at the program level: the closed recursive count
equals the compiled schedule's length — resource upper bounds can be
computed without materializing.
defdemoLayout
def demoLayout : SurgeryLayout
Layout on the `adder_d3` zone plan: data qubit `i` ↦ site `i` (Data
zone), ancilla qubit `k` ↦ site `100 + k` (tracked Ancilla zone).
defdemo_merge_x
def demo_merge_x : SurgeryGadget
X-type merge: ancilla X-check couples to both data qubits, 2 rounds.
defdemo_merge_z
def demo_merge_z : SurgeryGadget
Z-type merge: data Z-check couples to the ancilla, 3 rounds (deeper).
defdemo_inj
def demo_inj (j : Nat) : SurgeryGadget
Injection merges (the 3 surgery steps of one `teleportCCX`), each a
single-round single-ancilla merge on a DIFFERENT data qubit pair.
defdemoProgram
def demoProgram : QECProgram
The heterogeneous QEC program: merge ∥ CCZ injection ∥ merge.
theoremdemoProgram_wf
theorem demoProgram_wf : programWf demoProgram = true
defdemoCompiled
def demoCompiled : List SysCall
The compiled schedule: every SysCall derived from connection matrices,
clock and decoder rounds threaded by the driver.
theoremdemoCompiled_passes
theorem demoCompiled_passes :
checkScheduleOn adder_d3_magicStock demoCompiled = true*The compiled heterogeneous program PASSES the full system audit**
(gate support ∧ strict bundle: capacity, exclusivity, freshness,
decoder budget, I4 magic window, …) on the magic-stocked catalog
machine.
theoremdemoCompiled_decode_ids_unique
theorem demoCompiled_decode_ids_unique :
decode_ids_unique_ok demoCompiled = trueDecode ids are globally unique (instance of the §5 parametric law).
theoremdemoCompiled_fails_without_reaction_budget
theorem demoCompiled_fails_without_reaction_budget :
checkScheduleOn
{ adder_d3_magicStock with
decoderReconfigurability holds for compiled QEC programs too: the SAME
compiled schedule fails on a zero-reaction-budget machine.
theoremdemoCompiled_count
theorem demoCompiled_count :
demoCompiled.length = programSyscallCount demoProgramThe closed count matches the compiled length (instance of §6):
(7·2 + 1) merge-x ++ (1 + 3·(4·1 + 1)) injection ++ (4·3 + 1) merge-z
= 15 + 16 + 13 = 44 SysCalls.
theoremdemoCompiled_count_value
theorem demoCompiled_count_value : programSyscallCount demoProgram = 44
defge2021Layout
def ge2021Layout : SurgeryLayout
Patch-granular GE2021 layout: data patch `i` ↦ site `i`, routing/bus
patch `k` ↦ site `patches + k`.
defge2021_merge
def ge2021_merge (hz : List (List Bool)) (cx cz : List (List Bool))
(tp : List Bool) : SurgeryGadgetA d = 27 two-body merge (27 syndrome rounds, as the paper's lattice
surgery requires).
defge2021Probe
def ge2021Probe : QECProgram
The GE2021-shaped probe: X-merge ∥ CCZ injection ∥ Z-merge, all at
`tau_s = 27`.
defge2021ProbeCompiled
def ge2021ProbeCompiled : List SysCall
theoremge2021_probe_passes
theorem ge2021_probe_passes :
checkScheduleOn ge2021_logical ge2021ProbeCompiled = true*READY**: the d = 27 probe, compiled by the whole-program driver,
passes the full GE2021 system audit.
theoremge2021_probe_fails_without_reaction_budget
theorem ge2021_probe_fails_without_reaction_budget :
checkScheduleOn
{ ge2021_logical with
decoderThe paper's parameters are LIVE on this lane too: halving nothing
but the reaction budget to 0 µs kills the same compiled probe.
theoremge2021_probe_decode_ids_unique
theorem ge2021_probe_decode_ids_unique :
decode_ids_unique_ok ge2021ProbeCompiled = trueDecode rounds stay globally unique at d = 27 (5 gadgets × 27).
theoremge2021_probe_count
theorem ge2021_probe_count :
ge2021ProbeCompiled.length = programSyscallCount ge2021ProbeFormalRV.System.Compile.SurfaceSystemCompile
FormalRV/System/Compile/SurfaceSystemCompile.lean
FormalRV.System.SurfaceSystemCompile — distance-parametric surface-code
resource derivations plus a small system-level schedule check (one window,
five concurrent SysCalls), hardware-agnostic. This sketches the four design
questions of a surface-code Shor compilation in miniature; it is NOT a full
physical compilation of Shor.
## Hardware-agnostic by construction
There is NO `atom` abstraction here. The resource layer is parameterised by a
`Hardware` carrying only a cycle time, so it works for superconducting,
trapped-ion, OR neutral-atom machines — you plug the cycle time. The system
layer (`SysCall`: Gate/Measure/Transit/RequestMagicState/DecodeSyndrome; the
`baseInvariants`: capacity, exclusivity, latency, throughput, decoder) is
likewise hardware-neutral. HARDWARE-SPECIFIC connectivity/transport enters
ONLY as a pluggable `SpaceTimeInvariant` instance (neutral-atom rigid AOD move
is one such instance; a superconducting fixed-coupling rule would be another) —
it is never part of the core.
## The four questions (in miniature)
Q1 (logical→physical map) `patchLo/patchHi`: each logical qubit is a
disjoint contiguous block of physical qubit sites (`patches_disjoint`).
Q2 (ancilla scheduling) `dataSites/syndromeAncilla/routingAncilla`: a patch
budgets data + surgery-routing sites; `patch_site_accounts` records the
(definitional) split.
Q3 (T-factory scheduling) `magicProducedInWindow/factoryMeetsDemand`: a factory
making one magic state per `cyclesPerMagic` with `P` parallel copies;
demand ≤ production checked on a worked example.
Q4 (arbitrary distance) `surfaceCodeD d` = [[d²+(d-1)², 1, d]] for ANY d; the
resource derivation is distance-parametric (instantiated at d = 27).
## System-level check
`surfaceShorCtx_valid`: ONE window of five concurrent SysCalls (syndrome
extraction ∥ surgery merge ∥ magic request ∥ decode ∥ ancilla request) passes
`checkAll baseInvariants` on the demo architecture. The schedule has
`moves := []`, so the platform transport invariants below pass VACUOUSLY.
No `sorry`, no new `axiom`.
defsurfaceCodeD
def surfaceCodeD (d : Nat) : FormalRV.Framework.QECCode
The distance-`d` surface code [[d² + (d-1)², 1, d]] for ANY `d`.
theoremsurfaceCodeD_k
theorem surfaceCodeD_k (d : Nat) : (surfaceCodeD d).k = 1
theoremsurfaceCodeD_dist
theorem surfaceCodeD_dist (d : Nat) : (surfaceCodeD d).d = d
theoremsurfaceCodeD_physPer
theorem surfaceCodeD_physPer (d : Nat) :
physPerLogical (surfaceCodeD d) = (surfaceCodeD d).nphysical/logical for a `k = 1` surface code is its physical-qubit count `n`.
theoremsurface27_is_1405
theorem surface27_is_1405 :
(surfaceCodeD 27).n = 1405 ∧ (surfaceCodeD 27).d = 27
∧ physPerLogical (surfaceCodeD 27) = 1405*d = 27 instance** — the framework evaluates the real RSA-scale patch:
[[1405, 1, 27]], 1405 physical qubits per logical patch.
theoremsurfaceShor_qubits_anyD
theorem surfaceShor_qubits_anyD (d T L factory : Nat) (hw : Hardware) (ow p : Nat) :
(estimateWith (surfaceModel factory) hw (shorWorkload T L) (surfaceCodeD d) ow p).qubits
= L * (2 * (surfaceCodeD d).n) + factory*Distance-general qubit count.** For EVERY distance `d`, the surface-code
Shor footprint is `L` patches of `2·n(d)` physical qubits plus the factory.
theoremsurfaceShor_time_anyD
theorem surfaceShor_time_anyD (d T L factory : Nat) (hw : Hardware) (ow p : Nat) :
(estimateWith (surfaceModel factory) hw (shorWorkload T L) (surfaceCodeD d) ow p).time_us_tenths
= T * d * hw.cycle_time_us_tenths*Distance-general runtime.** `T` logical Toffolis, each `d` code cycles.
defpatchSize
def patchSize (d : Nat) : Nat
Physical sites per logical patch: data + an equal standing routing area
(`2 · physPerLogical`, the surface convention; gidney-ekera-2021 §2.14).
defpatchLo
def patchLo (i d : Nat) : Nat
First physical-site index of logical qubit `i`.
defpatchHi
def patchHi (i d : Nat) : Nat
One-past-last physical-site index of logical qubit `i`.
theorempatches_disjoint
theorem patches_disjoint (i j d : Nat) (h : i < j) : patchHi i d ≤ patchLo j d
*Q1 layout correctness: distinct logical qubits occupy DISJOINT physical
regions.** For `i < j`, qubit `i`'s block ends at or before `j`'s begins.
defdataSites
def dataSites (d : Nat) : Nat
Data sites of a patch (the code's physical-qubit count).
defsyndromeAncilla
def syndromeAncilla (d : Nat) : Nat
In-patch syndrome-extraction ancilla (one basis, qianxu `N = n + (n-k)/2`).
defroutingAncilla
def routingAncilla (d : Nat) : Nat
Standing surgery-routing area (where lattice-surgery merges happen).
theorempatch_site_accounts
theorem patch_site_accounts (d : Nat) :
patchSize d = dataSites d + routingAncilla d*Q2 accounting (definitional)**: a patch's sites split into data +
surgery-routing. Since `patchSize d = 2·n` and both summands equal `n`,
this is the arithmetic identity `2n = n + n` — it records the naming
convention (data block + equal standing routing area), not a non-trivial
budget. (Syndrome ancilla are bundled in the in-patch `physPerLogical`,
per the surface cost model.)
defmagicProducedInWindow
def magicProducedInWindow (parallelFactories cyclesPerMagic window : Nat) : Nat
Magic states a factory bank produces in a window: `P` parallel copies, each
one state per `cyclesPerMagic`, over `window` cycles.
deffactoryMeetsDemand
def factoryMeetsDemand (demand parallelFactories cyclesPerMagic window : Nat) : Bool
The factory bank meets the magic-state demand in the window.
deffactorySites
def factorySites (perFactory parallelFactories : Nat) : Nat
Physical sites of a factory bank: `perFactory` sites × `P` parallel copies.
theoremfactory_meets_demand_demo
theorem factory_meets_demand_demo :
factoryMeetsDemand 8 4 5 10 = true*Q3 worked schedule.** A factory making one magic state per 5 cycles, with
4 parallel copies, meets a demand of 8 magic states per 10-cycle window
(production = (10/5)·4 = 8).
theoremmagicProduced_mono
theorem magicProduced_mono (P P' cyclesPerMagic window : Nat) (h : P ≤ P') :
magicProducedInWindow P cyclesPerMagic window
≤ magicProducedInWindow P' cyclesPerMagic window*Monotone in parallelism**: more factory copies never reduce production.
FormalRV.System.Compile.SurgeryGadgetToSysCalls
FormalRV/System/Compile/SurgeryGadgetToSysCalls.lean
FormalRV.System.SurgeryGadgetToSysCalls — compilers from the
`LDPCSurgery.SurgeryGadget` qLDPC IR to `SysCall` streams that feed
the strengthened system-layer cert (`PPMScheduleCertWithFactoryPorts`
from `Compile/PPMScheduleContract.lean`).
## Platform-neutral terminology
The system layer is **NOT** specific to neutral atoms. A `SiteId` /
`PhysicalResourceId` may denote a superconducting physical qubit, a
trapped-ion zone/qubit, a neutral atom, a spin qubit, a qLDPC block
position, a lattice-surgery patch slot, or a factory output port —
depending on the hardware instantiation. Schedulable-gadget fields
here use **site** instead of **atom**. Legacy `atom`-named fields in
foundational code (`ScheduleInv.ArchZone.site_lo`, `site_hi`,
`total_sites`, `contains_atom`, `Architecture.syscall_acts_on`) are
RETAINED to avoid a dangerous global rename; read them as site /
physical-resource ids.
## Contents
§1–§8 simple compiler: `SchedulableSurgeryGadget` +
`compileSurgeryGadgetToSysCalls` (consumes only `tau_s`; fixed
two-data-site pattern; `5·tau_s + 1` SysCalls). By-construction
`rfl` agreement with the hand-written GE2021 `ppm_block_syscalls`
(`compile_basic_ppm_eq_existing_ppm_block`); cert existence via
`surgeryGadget_cert_of_valid`; parallel-aliasing rejected,
parallel-distinct / sequential-triple accepted; foldl-derived
wallclocks.
§9–§12 topology-aware compiler: `connEdges`,
`TopologySchedulableSurgeryGadget`,
`compileTopologySurgeryToSysCalls` — the `Gate2q` / `Measure`
stream is derived from the gadget's actual `conn_x` / `conn_z`
matrices and `ancilla_n`; demo gadget passes the existing qLDPC
structural verifier.
§13–§16 L3/system contract:
`verify_surgery_gadget_with_schedule` (qLDPC structural verifier
∧ strengthened system bundle), decomposition lemmas, cert
extraction, the bundled `verify_surgery_gadget_with_schedule_sound`;
instantiated on the topology demo and the corpus Steane X̄
surgery, with a negative sanity check.
Reuses (no re-implementation): `SurgeryGadget` from
`QEC/LatticeSurgery/LDPCSurgery.lean`; the cert, validator, builder,
and schedule combinators from `Compile/PPMScheduleContract.lean` /
`Core/ScheduleCombinators.lean`; `ppm_block_syscalls` and
`ge2021_ppm_arch` from `PPM/GE2021PPMSysInv.lean`.
## Verification boundary
Verified: SysCall compilation from L3 surgery-gadget descriptions;
definitional agreement of the simple compiler with the hand-written
GE2021 PPM block under matching parameters; strengthened system
invariants on compiled streams; derived wallclock/resource values.
NOT verified: quantum-semantic correctness of the PPM (whether the
lattice surgery actually measures the claimed Pauli product);
decoder algorithm correctness; physical derivation of per-SysCall
durations; schedule optimality; the full GE2021 schedule at
RSA-2048 scale.
No Mathlib. Pure Bool / Nat / List. Decidable.
abbrevPhysicalResourceId
abbrev PhysicalResourceId : Type
A generic physical-resource identifier (a qubit, an ion, an
atom, a slot — depends on the platform).
abbrevPhysicalQubitId
abbrev PhysicalQubitId : Type
A physical-qubit identifier.
abbrevSiteId
abbrev SiteId : Type
A generic site id (a slot in the data/ancilla/factory layout).
abbrevPatchSlotId
abbrev PatchSlotId : Type
A lattice-surgery patch slot id.
abbrevFactoryPortId
abbrev FactoryPortId : Type
A factory output port id (a logical "where a magic state
appears"; semantics is platform-dependent).
abbrevRoutingSiteId
abbrev RoutingSiteId : Type
A routing-graph site id.
structureSchedulableSurgeryGadget
structure SchedulableSurgeryGadget
A schedulable wrapper: an existing `SurgeryGadget` plus the
timing / physical-resource mapping context the compiler needs.
The compiler uses:
`gadget.tau_s` — number of stabilizer-extraction rounds.
`data_site_a`, `data_site_b` — two representative data
sites participating in the joint measurement. (For a
full qLDPC surgery the merge stabilizer touches many
more; this minimal compiler captures the worst-case
per-round resource-traffic pattern.)
`ancilla_site` — single ancilla site used across all
rounds (each round's `RequestFreshAncilla` re-initialises
it).
`start_us` — when the gadget's SysCall stream begins.
`decoder_id_base` — first decoder id; round `r` uses
`decoder_id_base + r`.
A `SiteId` here may denote a superconducting physical qubit,
a trapped-ion zone/qubit, a neutral atom, a spin qubit, or a
lattice-surgery patch slot — depending on the hardware
instantiation. See the file header for the
platform-neutrality note.
For a real `SurgeryGadget` instance the spec must reflect
the actual physical-resource layout; this minimal form is
enough to populate the strengthened cert.
defcompileSurgeryGadgetRound
def compileSurgeryGadgetRound
(s : SchedulableSurgeryGadget) (round_idx : Nat) : List SysCallOne round of stabilizer extraction: 5 SysCalls.
[t0, t0+1) RequestFreshAncilla
[t0+1, t0+2) Gate2q data_a → ancilla
[t0+2, t0+3) Gate2q data_b → ancilla
[t0+3, t0+4) Measure ancilla
[t0+4, t0+5) DecodeSyndrome
defcompileSurgeryGadgetToSysCalls
def compileSurgeryGadgetToSysCalls
(s : SchedulableSurgeryGadget) : List SysCallCompile the full gadget: `tau_s` rounds, then one
`PauliFrameUpdate` for the final Pauli correction.
Total SysCalls = `5 · tau_s + 1`.
theoremcompileSurgeryGadgetRound_length
theorem compileSurgeryGadgetRound_length
(s : SchedulableSurgeryGadget) (r : Nat) :
(compileSurgeryGadgetRound s r).length = 5Each round emits exactly 5 SysCalls.
theoremrounds_flatMap_length
private theorem rounds_flatMap_length (s : SchedulableSurgeryGadget) (n : Nat) :
((List.range n).flatMap (compileSurgeryGadgetRound s)).length = 5 * nThe flatMap-over-range part of the compiled stream has length
`5 · n` for any `n`. By induction on `n`.
theoremcompileSurgeryGadgetToSysCalls_length
theorem compileSurgeryGadgetToSysCalls_length
(s : SchedulableSurgeryGadget) :
(compileSurgeryGadgetToSysCalls s).length = 5 * s.gadget.tau_s + 1Total SysCall count: `5 · tau_s + 1`.
deftrivial_tau3_gadget
def trivial_tau3_gadget : SurgeryGadget
A trivial `SurgeryGadget` with `tau_s = 3` and otherwise
empty fields. Used solely to drive the SysCall compiler
structurally — the qLDPC structural verifier passes
vacuously on this gadget (empty codes), but the compiler
consumes only `tau_s`.
defge2021_basic_ppm_gadget_spec
def ge2021_basic_ppm_gadget_spec : SchedulableSurgeryGadget
The schedulable spec that, when compiled, exactly reproduces
`ppm_block_syscalls` (sites 0, 50, 100; start 0; decoder
base 0).
theoremcompile_basic_ppm_eq_existing_ppm_block
theorem compile_basic_ppm_eq_existing_ppm_block :
compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_spec
= ppm_block_syscallsDesign-intent consistency check (`rfl`): with parameters chosen
to mirror the hand-written block (sites 0/50/100, start 0,
decoder base 0), the compiler reproduces `ppm_block_syscalls`
definitionally. The compiler was written so that this holds —
it is a by-construction sanity check, not an independent
correspondence result.
theoremcompile_basic_ppm_all_invariants_ok
theorem compile_basic_ppm_all_invariants_ok :
all_invariants_with_factory_ports_ok
ge2021_ppm_arch
(compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_spec)
10 1000 1000 = trueThe compiler preserves the strengthened invariant bundle on
the matching spec — reuses the EXISTING
`ge2021_ppm_block_factory_exclusivity_ok` +
`ppm_block_all_invariants_ok` (after composing with the
strengthened bundle). Closed by `native_decide` (small
16-SysCall schedule).
theoremsurgeryGadget_cert_of_valid
theorem surgeryGadget_cert_of_valid
(arch : ZonedArch) (s : SchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : all_invariants_with_factory_ports_ok arch
(compileSurgeryGadgetToSysCalls s)
t_react_us window_us max_per_window = true) :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = arch
∧ cert.syscalls = compileSurgeryGadgetToSysCalls s
∧ cert.wallclock_us
= scheduleWallclockUs (compileSurgeryGadgetToSysCalls s)*Cert constructor for surgery gadgets**: whenever the
compiled SysCall stream of a `SchedulableSurgeryGadget`
passes the strengthened invariant bundle under the given
parameters, a `PPMScheduleCertWithFactoryPorts` exists with
matching fields and a derived wallclock.
REUSES `mkPPMScheduleCertWithFactoryPorts_of_valid` from
`PPMScheduleContract.lean` — no duplication of proof
unpacking.
theoremge2021_basic_ppm_surgery_cert_exists
theorem ge2021_basic_ppm_surgery_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = ge2021_ppm_arch
∧ cert.syscalls
= compileSurgeryGadgetToSysCalls ge2021_basic_ppm_gadget_specConcrete cert existence for the basic GE2021 PPM gadget.
defsurgery_ppm_A
def surgery_ppm_A : SchedulableSurgeryGadget
Good gadget A: data sites 0/50, ancilla site 100, start t=0.
defsurgery_ppm_B_distinct
def surgery_ppm_B_distinct : SchedulableSurgeryGadget
Good gadget B with DISTINCT ancilla (101): for parallel
composition.
defsurgery_ppm_C_distinct
def surgery_ppm_C_distinct : SchedulableSurgeryGadget
Good gadget C with another distinct ancilla (102).
defsurgery_ppm_B_alias
def surgery_ppm_B_alias : SchedulableSurgeryGadget
Bad gadget B with the SAME ancilla 100 as A: parallel
composition with A causes ancilla aliasing.
theoremsurgery_ppm_A_all_invariants_ok
theorem surgery_ppm_A_all_invariants_ok :
all_invariants_with_factory_ports_ok ge2021_ppm_arch
(compileSurgeryGadgetToSysCalls surgery_ppm_A) 10 1000 1000 = trueThe good gadget A's compiled stream passes the strengthened
bundle under the existing GE2021 architecture. By
construction `surgery_ppm_A` is the same spec as the basic
GE2021 one.
theoremsurgery_good_cert_exists
theorem surgery_good_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = compileSurgeryGadgetToSysCalls surgery_ppm_Adefsurgery_arch
def surgery_arch : ZonedArch
A larger architecture accommodating multiple parallel
surgery gadgets. 4 zones × 100 sites each, 400 sites total.
Ancilla zone big enough for the 3 ancilla sites used in the
triple example. (`total_sites` is the legacy field name on
`ScheduleInv.ZonedArch`; read it as "total sites" in
platform-neutral terms.)
defsurgery_pair_parallel_alias_syscalls
def surgery_pair_parallel_alias_syscalls : List SysCall
theoremsurgery_pair_parallel_alias_rejected
theorem surgery_pair_parallel_alias_rejected :
validateScheduleWithFactoryPorts
surgery_arch surgery_pair_parallel_alias_syscalls 10 1000 1000 = falseThe parallel-aliasing surgery pair is REJECTED by the
strengthened bundle (Gate2qs in concurrent rounds both claim
ancilla 100).
defsurgery_pair_parallel_distinct_syscalls
def surgery_pair_parallel_distinct_syscalls : List SysCall
theoremsurgery_pair_parallel_distinct_all_invariants_ok
theorem surgery_pair_parallel_distinct_all_invariants_ok :
all_invariants_with_factory_ports_ok surgery_arch
surgery_pair_parallel_distinct_syscalls 10 1000 1000 = truetheoremsurgery_pair_parallel_distinct_cert_exists
theorem surgery_pair_parallel_distinct_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls
= parSchedules
(compileSurgeryGadgetToSysCalls surgery_ppm_A)
(compileSurgeryGadgetToSysCalls surgery_ppm_B_distinct)defsurgery_triple_sequential_syscalls
def surgery_triple_sequential_syscalls : List SysCall
theoremsurgery_triple_sequential_all_invariants_ok
theorem surgery_triple_sequential_all_invariants_ok :
all_invariants_with_factory_ports_ok surgery_arch
surgery_triple_sequential_syscalls 10 1000 1000 = truetheoremsurgery_triple_sequential_cert_exists
theorem surgery_triple_sequential_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = surgery_triple_sequential_syscallstheoremsurgery_good_wallclock_is_derived
theorem surgery_good_wallclock_is_derived :
scheduleWallclockUs (compileSurgeryGadgetToSysCalls surgery_ppm_A)
= (compileSurgeryGadgetToSysCalls surgery_ppm_A).foldl
(fun acc sc => Nat.max acc sc.end_us) 0The good gadget's wallclock IS the foldl of its compiled
stream — not a typed-in number.
theoremsurgery_triple_wallclock_is_derived
theorem surgery_triple_wallclock_is_derived :
scheduleWallclockUs surgery_triple_sequential_syscalls
= surgery_triple_sequential_syscalls.foldl
(fun acc sc => Nat.max acc sc.end_us) 0Same for the triple schedule.
theoremsurgery_good_wallclock_value
theorem surgery_good_wallclock_value :
scheduleWallclockUs (compileSurgeryGadgetToSysCalls surgery_ppm_A) = 16Concrete wallclock values for the good gadget and triple.
theoremsurgery_triple_wallclock_value
theorem surgery_triple_wallclock_value :
scheduleWallclockUs surgery_triple_sequential_syscalls = 48defrowEdgesAux
def rowEdgesAux (i : Nat) : Nat → BoolVec → List (Nat × Nat) | _, [] => [] | j, true :: rest => (i, j) :: rowEdgesAux i (j + 1) rest | j, false :: rest => rowEdgesAux i (j + 1) rest
Tail-recursive helper: given a row index `i` and a starting
column position `j`, walk the BoolVec and emit `(i, k)` for
every position `k ≥ j` whose entry is `true`.
defconnEdgesAux
def connEdgesAux : Nat → BoolMat → List (Nat × Nat) | _, [] => [] | i, row :: rest => rowEdgesAux i 0 row ++ connEdgesAux (i + 1) rest
Walk a `BoolMat` and emit the `(row_idx, col_idx)` pairs of
every `true` entry, with row indices starting from `i`.
defconnEdges
def connEdges (conn : BoolMat) : List (Nat × Nat)
Computable edge-list extraction from a connection matrix.
Output: every `(i, j)` such that `conn[i][j] = true`, in
row-major order.
theoremconnEdges_empty
theorem connEdges_empty : connEdges ([] : BoolMat) = []
The empty connection matrix produces no edges.
structureTopologySchedulableSurgeryGadget
structure TopologySchedulableSurgeryGadget
A TOPOLOGY-aware schedulable wrapper. Unlike
`SchedulableSurgeryGadget` (which hard-codes two data sites
and one ancilla site), this wrapper carries SITE-MAPPING
FUNCTIONS that the compiler applies to the connection-matrix
indices to derive the actual physical-resource ids used in
each `Gate2q` / `Measure`.
Fields:
`gadget` — the underlying `SurgeryGadget`. All of its
structural fields (`data_code`, `ancilla_n`, `conn_x`,
`conn_z`, `tau_s`) are CONSUMED by the compiler.
`start_us` — when the gadget's SysCall stream begins.
`dataSite : Nat → SiteId` — maps a data-qubit index
`j ∈ {0, …, data_code.n - 1}` to its physical-resource
id.
`ancillaSite : Nat → SiteId` — maps an ancilla-qubit
index `i ∈ {0, …, ancilla_n - 1}` to its
physical-resource id.
`decoderBase : Nat` — first decoder id; round `r` uses
`decoderBase + r`.
`SiteId` is platform-neutral (see §0).
deftopologyRoundGateCount
def topologyRoundGateCount (s : TopologySchedulableSurgeryGadget) : Nat
Number of `Gate2q` calls one topology round emits = number
of `true` entries in `conn_x` plus number of `true` entries
in `conn_z`.
deftopologyRoundLength
def topologyRoundLength (s : TopologySchedulableSurgeryGadget) : Nat
Number of SysCalls one topology round emits:
1 RequestFreshAncilla + |edges_x| + |edges_z| +
ancilla_n Measures + 1 DecodeSyndrome
= `2 + |gates| + ancilla_n`.
defemitXEdgeGates
def emitXEdgeGates
(s : TopologySchedulableSurgeryGadget)
(t_start : Nat)
(edges : List (Nat × Nat)) : List SysCallEmit a per-edge `Gate2q` SysCall stream for the X-coupling
block. An X-edge `(i, j)` (ancilla X-check `i`, data qubit
`j`) emits `Gate2q (dataSite j) (ancillaSite i)` at the
given offset.
defemitZEdgeGates
def emitZEdgeGates
(s : TopologySchedulableSurgeryGadget)
(t_start : Nat)
(edges : List (Nat × Nat)) : List SysCallEmit a per-edge `Gate2q` SysCall stream for the Z-coupling
block. A Z-edge `(i, j)` (data Z-check `i`, ancilla qubit
`j`) emits `Gate2q (dataSite i) (ancillaSite j)` at the
given offset.
The role of `i`/`j` swaps relative to X-edges because of the
asymmetric matrix conventions in `LDPCSurgery.lean`: `conn_x`
cols are data, `conn_z` cols are ancilla.
defemitAncillaMeasures
def emitAncillaMeasures
(s : TopologySchedulableSurgeryGadget) (t_start : Nat) : List SysCallEmit one `Measure` SysCall per ancilla qubit.
defcompileTopologySurgeryRound
def compileTopologySurgeryRound
(s : TopologySchedulableSurgeryGadget) (round_idx : Nat) : List SysCallOne topology round emits:
[t0, t0+1) RequestFreshAncilla
[t0+1, t0+1+|ex|) Gate2q per X-edge
[t0+1+|ex|, t0+1+|ex|+|ez|) Gate2q per Z-edge
[..|gates|, ..|gates|+a) Measure per ancilla qubit
[t0+1+|gates|+a, t0+2+|gates|+a) DecodeSyndrome
Total per-round SysCalls = `topologyRoundLength s`.
defcompileTopologySurgeryToSysCalls
def compileTopologySurgeryToSysCalls
(s : TopologySchedulableSurgeryGadget) : List SysCallCompile a topology-aware schedulable gadget: `tau_s` rounds,
each derived from the actual connection matrices, plus one
final `PauliFrameUpdate`.
theoremcompileTopologySurgery_wallclock_is_derived
theorem compileTopologySurgery_wallclock_is_derived
(s : TopologySchedulableSurgeryGadget) :
scheduleWallclockUs (compileTopologySurgeryToSysCalls s)
= (compileTopologySurgeryToSysCalls s).foldl
(fun acc sc => Nat.max acc sc.end_us) 0The wallclock of the topology-compiled stream IS the foldl
over `end_us` — not a typed-in number.
deftopology_demo_gadget
def topology_demo_gadget : SurgeryGadget
A non-trivial gadget: 2 data qubits, 2 ancilla qubits, one
X-coupling edge `(0, 0)` (ancilla X-check #0 ↔ data qubit
#0), one Z-coupling edge `(0, 1)` (data Z-check #0 ↔ ancilla
qubit #1).
theoremtopology_demo_gadget_verifies
theorem topology_demo_gadget_verifies :
SurgeryGadget.verify_surgery_gadget topology_demo_gadget = trueThe demo gadget passes the EXISTING qLDPC structural
verifier from `LDPCSurgery.lean`. Closed by `native_decide`
on the small finite structure.
deftopology_demo
def topology_demo : TopologySchedulableSurgeryGadget
The demo schedulable wrapper: data sites 0/1, ancilla sites
100/101, start at t=0, decoder base 0.
theoremtopology_demo_x_edges
theorem topology_demo_x_edges :
connEdges topology_demo.gadget.conn_x = [(0, 0)]Edge-list correctness for the X-coupling.
theoremtopology_demo_z_edges
theorem topology_demo_z_edges :
connEdges topology_demo.gadget.conn_z = [(0, 1)]Edge-list correctness for the Z-coupling.
theoremtopology_demo_round_length
theorem topology_demo_round_length :
topologyRoundLength topology_demo = 6Per-round SysCall count: 1 ancilla request + 1 X-edge gate +
1 Z-edge gate + 2 ancilla measures + 1 decode = 6.
theoremtopology_demo_total_syscalls
theorem topology_demo_total_syscalls :
(compileTopologySurgeryToSysCalls topology_demo).length = 13Total SysCall count of the topology-compiled demo:
2 rounds × 6 per-round = 12, plus 1 PauliFrameUpdate.
theoremtopology_demo_all_invariants_with_factory_ports_ok
theorem topology_demo_all_invariants_with_factory_ports_ok :
all_invariants_with_factory_ports_ok surgery_arch
(compileTopologySurgeryToSysCalls topology_demo) 10 1000 1000 = trueThe topology-compiled demo stream passes the strengthened
system-layer invariant bundle on the larger surgery
architecture (`surgery_arch`).
theoremtopology_demo_cert_exists
theorem topology_demo_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = surgery_arch
∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_demoExistence of a strengthened cert for the topology-compiled
demo schedule.
theoremtopology_demo_wallclock_is_derived
theorem topology_demo_wallclock_is_derived :
scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo)
= (compileTopologySurgeryToSysCalls topology_demo).foldl
(fun acc sc => Nat.max acc sc.end_us) 0The topology-compiled demo's wallclock is foldl-derived.
theoremtopology_demo_wallclock_value
theorem topology_demo_wallclock_value :
scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo) = 13Concrete wallclock value: 6 µs × 2 rounds + 1 µs PauliFrameUpdate = 13.
defverify_surgery_gadget_with_schedule
def verify_surgery_gadget_with_schedule
(s : TopologySchedulableSurgeryGadget)
(arch : ZonedArch)
(t_react_us window_us max_per_window : Nat) : BoolThe combined verifier.
theoremtopology_demo_combined_verifies
theorem topology_demo_combined_verifies :
verify_surgery_gadget_with_schedule
topology_demo surgery_arch 10 1000 1000 = trueThe demo passes the combined verifier under
`(surgery_arch, 10, 1000, 1000)`.
deftopology_demo_alias
def topology_demo_alias : TopologySchedulableSurgeryGadget
A second topology-schedulable gadget with the SAME ancilla
sites as `topology_demo`: parallel composition causes
ancilla aliasing. Same structural gadget; different start
time and decoder base.
deftopology_pair_alias_syscalls
def topology_pair_alias_syscalls : List SysCall
theoremtopology_pair_alias_rejected
theorem topology_pair_alias_rejected :
validateScheduleWithFactoryPorts
surgery_arch topology_pair_alias_syscalls 10 1000 1000 = falseThe parallel-aliasing topology pair is REJECTED by the
strengthened bundle (concurrent rounds both claim ancilla
sites 100/101).
deftopology_demo_distinct
def topology_demo_distinct : TopologySchedulableSurgeryGadget
A topology-schedulable gadget with DISTINCT ancilla sites
from `topology_demo`: parallel composition is admissible.
deftopology_pair_distinct_syscalls
def topology_pair_distinct_syscalls : List SysCall
theoremtopology_pair_distinct_all_invariants_ok
theorem topology_pair_distinct_all_invariants_ok :
all_invariants_with_factory_ports_ok surgery_arch
topology_pair_distinct_syscalls 10 1000 1000 = truetheoremtopology_pair_distinct_cert_exists
theorem topology_pair_distinct_cert_exists :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = topology_pair_distinct_syscallstheoremverify_surgery_gadget_with_schedule_implies_gadget_ok
theorem verify_surgery_gadget_with_schedule_implies_gadget_ok
(arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : verify_surgery_gadget_with_schedule
s arch t_react_us window_us max_per_window = true) :
SurgeryGadget.verify_surgery_gadget s.gadget = trueIf the combined checker holds, the underlying
`SurgeryGadget` passes the existing qLDPC structural
verifier.
theoremverify_surgery_gadget_with_schedule_implies_schedule_ok
theorem verify_surgery_gadget_with_schedule_implies_schedule_ok
(arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : verify_surgery_gadget_with_schedule
s arch t_react_us window_us max_per_window = true) :
SurgeryGadget.verify_surgery_schedule [s.gadget] = trueIf the combined checker holds, the underlying gadget — as a
one-element schedule — passes the qLDPC schedule verifier.
(The schedule verifier just maps `verify_surgery_gadget`
over every gadget in the list.)
theoremverify_surgery_gadget_with_schedule_implies_system_ok
theorem verify_surgery_gadget_with_schedule_implies_system_ok
(arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : verify_surgery_gadget_with_schedule
s arch t_react_us window_us max_per_window = true) :
all_invariants_with_factory_ports_ok arch
(compileTopologySurgeryToSysCalls s)
t_react_us window_us max_per_window = trueIf the combined checker holds, the topology-compiled SysCall
stream passes the strengthened system-layer invariant
bundle.
theoremverify_surgery_gadget_with_schedule_cert_exists
theorem verify_surgery_gadget_with_schedule_cert_exists
(arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : verify_surgery_gadget_with_schedule
s arch t_react_us window_us max_per_window = true) :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = arch
∧ cert.syscalls = compileTopologySurgeryToSysCalls s
∧ cert.t_react_us = t_react_us
∧ cert.window_us = window_us
∧ cert.max_per_window = max_per_window
∧ cert.wallclock_us*Main contract theorem.** If the combined checker
returns `true` on a topology-schedulable gadget, then a
strengthened cert exists with EXACTLY the input parameters
and the wallclock derived from the compiled stream by
`scheduleWallclockUs`.
Reuses
`mkPPMScheduleCertWithFactoryPorts_of_valid` — no
duplication of the 7-fold invariant unpacking.
theoremverify_surgery_gadget_with_schedule_sound
theorem verify_surgery_gadget_with_schedule_sound
(arch : ZonedArch) (s : TopologySchedulableSurgeryGadget)
(t_react_us window_us max_per_window : Nat)
(h : verify_surgery_gadget_with_schedule
s arch t_react_us window_us max_per_window = true) :
SurgeryGadget.verify_surgery_gadget s.gadget = true
∧ SurgeryGadget.verify_surgery_schedule [s.gadget] = true
∧ all_invariants_with_factory_ports_ok arch
(compileTopologySurgeryToSysCalls s)
t_react_us window_us max_per_window = true
∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = compileTopologySurgeryToSysCalls s*The paper-facing contract theorem.** If the combined
Boolean checker returns `true`, then:
(1) the qLDPC `SurgeryGadget` passes the existing
structural verifier;
(2) the same gadget — as a one-element schedule — passes
the qLDPC schedule verifier;
(3) the topology-compiled SysCall stream passes the
strengthened system-layer invariant bundle (I1-I4 +
factory-port exclusivity); AND
(4) a `PPMScheduleCertWithFactoryPorts` exists whose
`syscalls` field is exactly the compiled stream.
deftopology_demo_arch
def topology_demo_arch : ZonedArch
The demo architecture — alias for `surgery_arch`. Stated
as a separate `def` so the demo theorems quote a
"demo-named" parameter rather than the generic
`surgery_arch`.
deftopology_demo_t_react_us
def topology_demo_t_react_us : Nat
Standard decoder-react budget for the demos: 10 µs.
deftopology_demo_window_us
def topology_demo_window_us : Nat
Standard throughput window for the demos: 1000 µs.
deftopology_demo_max_per_window
def topology_demo_max_per_window : Nat
Standard max syscalls per window for the demos.
theoremtopology_demo_combined_verifies_alias
theorem topology_demo_combined_verifies_alias :
verify_surgery_gadget_with_schedule
topology_demo topology_demo_arch
topology_demo_t_react_us topology_demo_window_us
topology_demo_max_per_window = trueThe topology demo passes the combined verifier under the
demo parameters. Re-stated from
`topology_demo_combined_verifies` so it quotes the demo
aliases rather than the literals.
theoremtopology_demo_sound
theorem topology_demo_sound :
SurgeryGadget.verify_surgery_gadget topology_demo.gadget = true
∧ SurgeryGadget.verify_surgery_schedule [topology_demo.gadget] = true
∧ all_invariants_with_factory_ports_ok topology_demo_arch
(compileTopologySurgeryToSysCalls topology_demo)
topology_demo_t_react_us topology_demo_window_us
topology_demo_max_per_window = true
∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = compileTopologySurgeryToSysCalls topology_demo*Demo instantiation of the bundled contract theorem.**
theoremtopology_demo_cert_from_combined_verifier
theorem topology_demo_cert_from_combined_verifier :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = topology_demo_arch
∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_demo
∧ cert.wallclock_us
= scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_demo)*Demo cert extraction**: the topology demo yields a
strengthened cert whose wallclock is derived from its
compiled stream.
deftopology_steane_x
def topology_steane_x : TopologySchedulableSurgeryGadget
The Steane X-surgery gadget wrapped as a topology
schedulable. Reuses
`FormalRV.LatticeSurgery.SurgeryDemoSteane.steane_x_surgery`.
theoremtopology_steane_x_x_edges
theorem topology_steane_x_x_edges :
connEdges topology_steane_x.gadget.conn_x = [(0, 3), (0, 5), (0, 6)]Edge-count sanity: the Steane X-surgery has 3 X-edges
(row 0 of `conn_x` touches data qubits 3, 5, 6; row 1 is
all-zero) and 0 Z-edges (the Z-coupling matrix is all
false). Closed by `decide` since `topology_steane_x` and
its underlying gadget are `def`s (no `@[reducible]`); both
sides are concrete and decidable.
theoremtopology_steane_x_z_edges
theorem topology_steane_x_z_edges :
connEdges topology_steane_x.gadget.conn_z = []theoremtopology_steane_x_round_length
theorem topology_steane_x_round_length :
topologyRoundLength topology_steane_x = 6Per-round SysCall count: 1 ancilla request + 3 X-edge gates
+ 0 Z-edge gates + 1 ancilla measure + 1 decode = 6.
theoremtopology_steane_x_combined_verifies
theorem topology_steane_x_combined_verifies :
verify_surgery_gadget_with_schedule
topology_steane_x topology_demo_arch
topology_demo_t_react_us topology_demo_window_us
topology_demo_max_per_window = trueThe Steane topology gadget passes the combined verifier on
`topology_demo_arch`.
theoremtopology_steane_x_sound
theorem topology_steane_x_sound :
SurgeryGadget.verify_surgery_gadget topology_steane_x.gadget = true
∧ SurgeryGadget.verify_surgery_schedule [topology_steane_x.gadget] = true
∧ all_invariants_with_factory_ports_ok topology_demo_arch
(compileTopologySurgeryToSysCalls topology_steane_x)
topology_demo_t_react_us topology_demo_window_us
topology_demo_max_per_window = true
∧ ∃ cert : PPMScheduleCertWithFactoryPorts,
cert.syscalls = compileTopologySurgeryToSysCalls topology_steane_x*Corpus instantiation of the bundled contract theorem.**
theoremtopology_steane_x_cert_from_combined_verifier
theorem topology_steane_x_cert_from_combined_verifier :
∃ cert : PPMScheduleCertWithFactoryPorts,
cert.arch = topology_demo_arch
∧ cert.syscalls = compileTopologySurgeryToSysCalls topology_steane_x
∧ cert.wallclock_us
= scheduleWallclockUs (compileTopologySurgeryToSysCalls topology_steane_x)*Corpus cert extraction.**
theoremtopology_alias_pair_system_not_ok
theorem topology_alias_pair_system_not_ok :
all_invariants_with_factory_ports_ok
topology_demo_arch topology_pair_alias_syscalls
topology_demo_t_react_us topology_demo_window_us
topology_demo_max_per_window = falseFormalRV.System.Compose.VerifiedWorkloadBridge
FormalRV/System/Compose/VerifiedWorkloadBridge.lean
FormalRV.System.Compose.VerifiedWorkloadBridge — closing the three "seams" that
kept the Shor pipeline from being one composed chain.
The study (`ftq_vm/out/shorstudy/STUDY.md`) caught that, although every pillar is
individually axiom-clean and scalable to RSA-2048, the System layer was welded to the
circuit by a hand-typed paper literal, with the resource/runtime numbers sitting on a
different* object than any verified circuit, and the runtime ignoring the circuit's depth.
This module makes the resource & runtime numbers come AFTER an actually-composed circuit.
## What is closed here (and what is NOT — honest tiering, per CLAUDE.md)
**Seam 1 (literal).** `verifiedToffoli` is NO LONGER a hand-typed number: it is
`:=`-equal (`verifiedToffoli_eq_composed_circuit`) to `EGate.toffoli` of the *composed*
`WindowedComposed.modExp` circuit — the Toffoli count is the output of a circuit theorem
(`WindowedComposedCost.rsa2048_structural_circuit_toffoli`). The old `magicBudget`
literal (`Params/RSA2048`) is shown to be exactly the paper cost-model formula
(`magicBudget_is_paper_formula`, `= WindowedCostModel.toffoliCount 2048 3072 11`) and a
proven upper bound* on the composed-circuit count (`verifiedToffoli_le_magicBudget`,
+1.67 % = runway-folding + lookup-rounding the bare composed circuit omits).
**Seam 2 (different circuits).** The resource count fed to the System layer here is the
count of the SAME object the windowed pipeline builds (`WindowedComposed.modExp`, composed
from `babbushLookupAdd` primitives), and it flows 1:1 into the proved PPM magic-state
formula (`verifiedToffoli_CCZMagic`) and into the factory provisioning
(`verifiedFactoriesNeeded`, derived from THIS count, `≤` the provisioned 1093).
HONEST RESIDUE: `WindowedComposed.modExp`'s full *semantics* (that it computes `aˣ mod N`)
is verified per-primitive (`WindowedCircuitExec` / `MeasUncomputeExec`), NOT yet as one
composed theorem; and the N-generic *semantic* headline
(`VerifiedShorTheorem.Shor_correct_verified_no_modmult_axioms`) is still about the
un-windowed SQIR circuit. So this closes "resource count on a composed circuit", not
"windowed semantics composed into one theorem". That composition remains the open work.
**Seam 3 (free depth).** The depth is no longer a free parameter behind an undischarged
hypothesis: `reactionLimitedDepthUs := verifiedToffoli * reactionUs` is the
reaction-limited critical-path depth derived from the composed circuit's own count, and
`depth_below_magic_pipeline` DISCHARGES the magic-limited hypothesis at the REAL factory
count `F = 1093` (not `F = 1`), so `windowed_rsa2048_runtime_concrete` gives a concrete
runtime in which the circuit's count genuinely enters the depth.
HONEST RESIDUE: the reaction-limited model (one reaction round per critical-path Toffoli)
is the standard GE2021 assumption; it is NAMED here, not a free knob, but it still assumes
the data block parallelises enough that magic supply — not a serial `EGate` fold — binds.
No `sorry`, no new `axiom`. Numeric facts use `native_decide` (consistent with the rest of
`System/`); the structural/circuit facts are `rfl`/`rw` on proved theorems.
defverifiedToffoli
def verifiedToffoli : Nat
The RSA-2048 windowed mod-exp Toffoli count, defined to be the count of the *actually
composed* `WindowedComposed.modExp` circuit (window `w = 10`, `bits = 2048`,
`numMults = 246`, `numWin = 1024`). This is the number the System layer should consume.
theoremverifiedToffoli_eq_composed_circuit
theorem verifiedToffoli_eq_composed_circuit (W : Nat) (T : Nat → Nat) :
EGate.toffoli (modExp 10 W 2048 T 246 1024) = verifiedToffoli*★ Seam 1 closed ★** — `verifiedToffoli` is `=` the `EGate.toffoli` of a composed circuit,
for ANY window layout `W` and lookup table `T` (the Toffoli count is layout-independent).
The resource number is the output of a circuit theorem, not a hand-typed literal.
theoremverifiedToffoli_eq_value_correct_circuit
theorem verifiedToffoli_eq_value_correct_circuit
(W : Nat) (Tfam : Nat → Nat → Nat → Nat) (q_start : Nat) :
EGate.toffoli (modExpAt 10 W 2048 Tfam q_start 246 1024) = verifiedToffoli*★ Seam 1+2, on the VALUE-CORRECT circuit ★** — the same `verifiedToffoli` count is the
`EGate.toffoli` of `WindowedComposedAt.modExpAt`, the shared-accumulator, layout-correct
rebuild whose per-multiply-add VALUE is proven (`WindowedComposedAt.multiplyAddAt_fold`:
one multiply-add computes `(a·y) mod 2^bits`). `WindowedComposed.modExp` (above) has the
same count but is PROVEN value-broken for `W ≥ 2` (`MeasUncomputeValue.babbushLookupAdd_misses_table`),
so for the resource-on-a-semantically-meaningful-circuit reading this is the object to use.
The two counts are equal (`WindowedComposedAt.toffoli_modExpAt_eq_modExp`).
theoremmagicBudget_is_paper_formula
theorem magicBudget_is_paper_formula :
(FormalRV.System.RSA2048.magicBudget : ℚ) = toffoliCount 2048 3072 11The `Params/RSA2048.magicBudget` literal equals exactly the paper's windowed cost-model
formula `toffoliCount 2048 3072 11` — so it is not an unexplained number either.
theoremverifiedToffoli_le_magicBudget
theorem verifiedToffoli_le_magicBudget :
verifiedToffoli ≤ FormalRV.System.RSA2048.magicBudget*The paper budget dominates the composed circuit.** `2 578 993 152 ≤ 2 622 824 448`:
the System's provisioning budget is a verified upper bound on the actual composed circuit's
Toffoli count, so any provisioning sized for `magicBudget` covers the verified circuit.
theoremcomposed_circuit_within_budget
theorem composed_circuit_within_budget (W : Nat) (T : Nat → Nat) :
EGate.toffoli (modExp 10 W 2048 T 246 1024) ≤ FormalRV.System.RSA2048.magicBudgetThe composed circuit's Toffoli count, for any `W`/`T`, is within the System magic budget.
theoremverifiedToffoli_CCZMagic
theorem verifiedToffoli_CCZMagic :
numCCZMagic (circuitToPPM 8 (modmultBlock verifiedToffoli 0)) = verifiedToffoliThe CCZ magic states consumed equal the composed circuit's Toffoli count, via the
induction-proved PPM resource formula (no list of that length is ever built).
theoremverifiedToffoli_Meas
theorem verifiedToffoli_Meas :
numMeas (circuitToPPM 8 (modmultBlock verifiedToffoli 0)) = 3 * verifiedToffoliZ-basis syndrome measurements = 3× the composed circuit's Toffoli count.
defverifiedFactoriesNeeded
def verifiedFactoriesNeeded : Nat
CCZ factories needed for the 8-hour budget, sized for the COMPOSED-CIRCUIT count
(`verifiedToffoli`) rather than the paper literal — the tight provisioning.
theoremverifiedFactoriesNeeded_value
theorem verifiedFactoriesNeeded_value : verifiedFactoriesNeeded = 1075
The composed-circuit-tight factory count is `1075` (vs the paper-budget `1093`).
theoremverifiedFactories_le_provisioned
theorem verifiedFactories_le_provisioned :
verifiedFactoriesNeeded ≤ FormalRV.System.RSA2048.factoriesNeededThe tight provisioning fits inside the provisioned `1093` factories
(`Params/RSA2048.factoriesNeeded`): the device as built covers the verified circuit.
defreactionLimitedDepthUs
def reactionLimitedDepthUs : Nat
The reaction-limited critical-path depth derived from the composed circuit's OWN count:
one reaction round (`reactionUs = 10 µs`) per critical-path Toffoli. No free parameter.
theoremreactionLimitedDepthUs_value
theorem reactionLimitedDepthUs_value : reactionLimitedDepthUs = 25789931520
The depth in µs: `2 578 993 152 · 10 = 25 789 931 520 µs ≈ 7.16 h`.
theoremdepth_below_magic_pipeline
theorem depth_below_magic_pipeline :
reactionLimitedDepthUs ≤
deliveryLatency ccz_spec_qianxu 15
+ magicSupplyTimeUs verifiedToffoli 1093 ccz_spec_qianxu*★ Seam 3 closed ★** — at the REAL factory count `F = 1093`, the circuit-derived depth
is below the magic-supply pipeline (`12015 + ⌈K/1093⌉·12000`). This is the hypothesis the
device-feasibility theorem left UNDISCHARGED; here it is a proven fact, not an assumption.
theoremwindowed_rsa2048_runtime_concrete
theorem windowed_rsa2048_runtime_concrete :
circuitRuntimeUs reactionLimitedDepthUs verifiedToffoli 1093 ccz_spec_qianxu 15
= deliveryLatency ccz_spec_qianxu 15
+ magicSupplyTimeUs verifiedToffoli 1093 ccz_spec_qianxu*★ The concrete whole-circuit runtime ★**, at the real `F = 1093` factories and the
circuit-derived depth — NO free `logicalDepthUs`, NO undischarged hypothesis. The runtime
is the magic pipeline because the proven `depth_below_magic_pipeline` puts us in that regime.
theoremwindowed_rsa2048_runtime_value
theorem windowed_rsa2048_runtime_value :
circuitRuntimeUs reactionLimitedDepthUs verifiedToffoli 1093 ccz_spec_qianxu 15
= 28314672015The runtime as a literal: `12015 + 28 314 660 000 = 28 314 672 015 µs ≈ 7.87 h`
(the magic-supply pipeline at 1093 factories dominates the 7.16 h reaction-limited depth).
theoremrsa2048_resource_after_composed_circuit
theorem rsa2048_resource_after_composed_circuit (W : Nat) (T : Nat → Nat) :
EGate.toffoli (modExp 10 W 2048 T 246 1024) = verifiedToffoli
∧ verifiedToffoli ≤ FormalRV.System.RSA2048.magicBudget
∧ numCCZMagic (circuitToPPM 8 (modmultBlock verifiedToffoli 0)) = verifiedToffoli
∧ verifiedFactoriesNeeded ≤ FormalRV.System.RSA2048.factoriesNeeded
∧ circuitRuntimeUs reactionLimitedDepthUs verifiedToffoli 1093 ccz_spec_qianxu 15
= deliveryLatency ccz_spec_qianxu 15
+ magicSupplyTimeUs verifiedToffoli 1093 ccz_spec_qianxu*★ ONE chain, composed circuit → resource → device → runtime ★** (for any window layout
`W` and table `T`):
1. the workload IS `EGate.toffoli` of the composed `WindowedComposed.modExp`;
2. the paper magic budget dominates it (provisioning is sufficient);
3. it flows 1:1 into the proved PPM magic-state count;
4. the factory provisioning derived from THIS count fits the device's 1093 factories;
5. and the whole-circuit runtime, at 1093 factories with the circuit-derived depth, is the
concrete magic pipeline — the depth is no longer free and the hypothesis is discharged.
What this does NOT claim (honest residue): the windowed circuit's end-to-end *semantics*
composed into one theorem, nor that 1093 (paper) = 1075 (tight).
FormalRV.System.Core.Architecture
FormalRV/System/Core/Architecture.lean
FormalRV.System.Architecture — cross-platform architecture
abstraction for fault-tolerant quantum computers.
Applies uniformly to neutral-atom, trapped-ion, and
superconducting / spin platforms. All concrete numerical values
are paper-cited; no hallucinated hardware parameters.
Three primitives.
**Zone** — a region of qubits with a role and a finite capacity.
Internal layout is approximated by an `avg_internal_routing_us`
field for first-pass abstraction (a cited average over a real
layout, not invented).
**Channel** — a bus between two zones, with bandwidth (qubits/ms),
latency (µs), and fidelity (× 10^6). Channels are NOT perfect;
every transit accumulates a fidelity factor.
**SysCall** — a primitive operation the programmer schedules
explicitly. Includes not only gates but also DecodeSyndrome and
PauliFrameUpdate — they MUST appear in the schedule between
other operations to make wallclock accountable.
Three example instantiations are provided at the end with cited
numerical values from:
Neutral atom: ZAC `hardware_spec/toy_architecture.json` +
simulator defaults (Lin, Tan, Cong HPCA 2025);
Bluvstein 2024 (Nature 626) for atom-transfer kinematics.
Trapped ion: Pino et al. 2021 Nature 592, 209
("Trapped-ion CCD computer architecture", Quantinuum H1).
Superconducting: Krantz et al. 2019 Appl. Phys. Rev. 6, 021318
("Quantum engineer's guide to superconducting qubits"),
with IBM Eagle / Google Sycamore representative values.
The verification predicate `verifies arch sched` is platform-
independent: each platform fills in its own numerical values and
the same invariants apply unchanged.
No Mathlib dependency. Nat-only.
inductiveZoneRole
inductive ZoneRole | Memory -- long-term storage of logical qubits | Processor --
Functional role of a zone. Cross-platform.
instanceBEq
instance : BEq ZoneRole
structureZone
structure Zone
A zone: identifier + role + capacity + an average internal
routing time. The average value is meant to summarize a real
layout (e.g. "for a 100x100 SLM grid with 3 µm spacing, average
atom-to-atom transit is 15 µs"); the framework's first-pass
verifier treats the zone as opaque modulo this average.
inductiveChannelKind
inductive ChannelKind | AncillaSupply -- Ancilla zone → Processor (fresh helpers) | MagicSupply -- Factory zone → Processor (T / CCZ states) | MemorySave -- Processor → Memory (commit logical qubit) | MemoryLoad -- Memory → Processor (fetch logical qubit) | InterRouting -- generic transit (any-to-any) deriving DecidableEq, Repr
Kind of bus between two zones. Each kind has its own
expected pattern of use.
instanceBEq
instance : BEq ChannelKind
structureChannel
structure Channel
A channel: connects two zones. Three quantitative attributes:
`bandwidth_per_ms` — maximum number of qubits the channel can
transit per millisecond.
`latency_us` — single-transit duration.
`fidelity_x1e6` — fidelity per transit, scaled by 10^6 (i.e.
`999000` ↦ 0.999). Channels are *not* perfect; every transit
multiplies a fidelity factor into the circuit's total fidelity.
inductiveSysCallKind
inductive SysCallKind
/-- Single-qubit gate, parameterised by gate id. -/
| Gate1q (qubit : Nat) (gate_id : Nat)
/-- Two-qubit gate (e.g. CZ, MS, CR). -/
| Gate2q (q1 q2 : Nat) (gate_id : Nat)
/-- Single-qubit projective measurement (Z-basis default; `basis`
indexes alternative bases like X, Y). Non-unitary; produces
a classical bit. Required for magic-state injection and
syndrome readout. -/
| Measure (qubit : Nat) (basis : Nat)
/-- Transit a qubit through a channel between zones. -/
| TransitQubit (qubit : Nat) (channel_id : Nat)structureSysCall
structure SysCall
A scheduled SysCall instance with begin / end timestamps.
abbrevSchedule
abbrev Schedule
A schedule: an ordered list of SysCalls. Times are absolute.
structureArchitecture
structure Architecture
The architecture: zones + channels + a small set of global
hardware parameters. Per-channel quantities (bandwidth,
latency, fidelity) live on each `Channel`.
deffind_zone
def find_zone (arch : Architecture) (zid : Nat) : Option Zone
Look up a zone by id.
deffind_channel
def find_channel (arch : Architecture) (cid : Nat) : Option Channel
Look up a channel by id.
defSysCall.duration_us
def SysCall.duration_us (sc : SysCall) : Nat
Duration of a SysCall.
deflatency_ok
def latency_ok (arch : Architecture) (sched : Schedule) : Prop
*Latency invariant.** Every `TransitQubit` SysCall lasts at
least `channel.latency_us`; every `DecodeSyndrome` SysCall lasts
at most `arch.t_react_us`; every other SysCall has non-negative
duration.
This is the "logical-bug check": faster-than-channel transit or
too-slow decoder violates causality, regardless of hardware
speed.
defcapacity_ok
def capacity_ok (arch : Architecture) (sched : Schedule) : Prop
*Capacity invariant.** At every cycle, every zone holds at
most `zone.capacity` qubits. We approximate this here by
bounding the COUNT of active SysCalls that target a zone. A
proper per-cycle witness would require a per-time-instant
counting; this coarse version catches schedules that
structurally over-subscribe a zone.
defchannel_bandwidth_ok
def channel_bandwidth_ok (arch : Architecture) (sched : Schedule) : Prop
*Channel-bandwidth invariant.** Over the FULL schedule, the
number of transits through any channel is at most
`bandwidth_per_ms × (total_us / 1000)`. For first-pass we use
the total schedule duration as the window.
defverifies
def verifies (arch : Architecture) (sched : Schedule) : Prop
The headline verification predicate. Schedule `sched` is
verifiable on architecture `arch` iff all three invariants hold.
abbrevInitialPlacement
abbrev InitialPlacement
Initial qubit placement: a list of `(qubit_id, zone_id)` pairs.
defInitialPlacement.zone_of
def InitialPlacement.zone_of (placement : InitialPlacement) (qubit : Nat) :
Option NatLookup a qubit's initial zone.
deflatest_transit_for_qubit
def latest_transit_for_qubit (sched : Schedule) (qubit : Nat) (t : Nat) :
Option (Nat × Nat)Find the latest TransitQubit SysCall for `qubit` with
`end_us ≤ t`. Returns the (channel_id, end_us) pair.
defqubit_zone_at
def qubit_zone_at (placement : InitialPlacement) (arch : Architecture)
(sched : Schedule) (qubit : Nat) (t : Nat) : Option NatThe zone occupied by `qubit` at time `t`, given initial
placement and schedule.
defzone_occupancy_at
def zone_occupancy_at (placement : InitialPlacement) (arch : Architecture)
(sched : Schedule) (z_id : Nat) (t : Nat) (qubit_universe : List Nat) :
NatCount of qubits currently in zone `z` at time `t`.
deftransit_boundaries
def transit_boundaries (sched : Schedule) : List Nat
Boundary time points where occupancy may change: the begin_us
and end_us of every TransitQubit syscall.
defcapacity_ok_strict
def capacity_ok_strict (placement : InitialPlacement) (arch : Architecture)
(sched : Schedule) (qubit_universe : List Nat) : Prop*Strict per-zone capacity invariant.** At every transit
boundary time `t`, every zone holds at most its capacity.
defqubit_discarded_at
def qubit_discarded_at (sched : Schedule) (qubit : Nat) (t : Nat) : Bool
True if `qubit` has been measured (and therefore discarded)
by time `t`.
defqubit_alive_at
def qubit_alive_at (sched : Schedule) (qubit : Nat) (t : Nat) : Bool
True if `qubit` is alive at time `t` (still has a physical slot).
defzone_occupancy_at_alive
def zone_occupancy_at_alive (placement : InitialPlacement)
(arch : Architecture) (sched : Schedule) (z_id : Nat) (t : Nat)
(qubit_universe : List Nat) : NatZone occupancy counting ONLY alive qubits. Use this in place
of the naive `zone_occupancy_at` for any schedule that includes
`Measure` SysCalls.
defcapacity_ok_strict_alive
def capacity_ok_strict_alive (placement : InitialPlacement)
(arch : Architecture) (sched : Schedule)
(qubit_universe : List Nat) : Prop*Strict capacity invariant with qubit discard.** At every
SysCall boundary, every zone holds at most its capacity of
ALIVE qubits. This is the refined version of
`capacity_ok_strict` that respects the qubit lifecycle.
defdecoder_queue_depth_at
def decoder_queue_depth_at (sched : Schedule) (t : Nat) : Nat
Number of `DecodeSyndrome` SysCalls active at time `t`.
defdecoder_queue_ok
def decoder_queue_ok (sched : Schedule) (n_decoders : Nat) : Prop
*Decoder-queue invariant.** At every relevant boundary time,
the active decoder count is at most `n_decoders`.
defsyscall_precondition_met
def syscall_precondition_met
(placement : InitialPlacement) (arch : Architecture)
(sched : Schedule) (sc : SysCall) : BoolBoolean precondition for a single SysCall: structural
requirements that the schedule context must satisfy at the
SysCall's `begin_us`.
defsemantically_correct
def semantically_correct
(placement : InitialPlacement) (arch : Architecture)
(sched : Schedule) : Bool*Structural precondition check.** Every SysCall has its
structural precondition (`syscall_precondition_met`) met in
the schedule's context. Despite the name, this checks NO
unitary semantics: passing says nothing about which quantum
operation the schedule implements, only that each SysCall is
well-formed where it fires.
A schedule that fails this check is not just inefficient —
it does not represent a valid quantum operation on any
hardware, so resource verification (capacity, latency,
bandwidth, fidelity) on it is meaningless.
defper_ccz_atom_demand_per_role
def per_ccz_atom_demand_per_role : Nat
For the chained-CCZ pattern, each CCZ requires 3 Processor
and 3 Factory qubits. This is the per-CCZ atom demand.
defmax_ccz_parallelism
def max_ccz_parallelism (arch : Architecture) : Nat
Maximum CCZ-parallelism the architecture can sustain, derived
from the minimum of Processor and Factory capacities.
defmin_runtime_us
def min_runtime_us (arch : Architecture) (n_ccz : Nat)
(tau_ccz_us : Nat) : NatLower bound on runtime to execute `n_ccz` CCZ gates on the
architecture. Assumes the single-CCZ runtime is given as
`tau_ccz_us` (e.g., 263 µs for the ShorCCZGate schedule).
Runtime is `n_ccz · τ_ccz / P` where P is the maximum
parallelism the architecture sustains.
structureMagicStateSpec
structure MagicStateSpec
Cost specification for one magic state. All values
paper-cited at the point of instantiation.
defccz_spec_qianxu
def ccz_spec_qianxu : MagicStateSpec
The |CCZ⟩ magic-state specification under the qianxu
(Cain–Xu 2026) cost model, Appendix C.
| Field | Value | Citation |
|----------------------|------------|-------------------------------------|
| factory_qubits | 2565 | qianxu §App. C line 1386 |
| production_us | 12000 | 12 stabilizer cycles × 1 ms/cycle |
| success_rate_x1e6 | 800000 | ≈ 1/1.25 cultivation attempts |
| output_fidelity_x1e6 | 999999 | p_CCZ ≈ 10⁻¹⁰ ⇒ fidelity ≈ 1 − 10⁻⁶ ppm |
The 12-cycles-per-CCZ figure is qianxu's
`time_per_|CCZ⟩ = 120 cycles / 10 outputs = 12 cycles`
(qianxu line 1389), at the 1 ms cycle time qianxu p. 5
posits. Hence `production_us = 12000`.
deft_spec_qianxu
def t_spec_qianxu : MagicStateSpec
The |T⟩ cultivated magic-state spec (cited at qianxu line
1387: each |T⟩ cultivation ≈ 5 stab cycles, p_T ≈ 10⁻⁶).
inductiveLogicalGateKind
inductive LogicalGateKind
/-- Logical Hadamard on a single logical qubit. -/
| LH (q : Nat)
/-- Logical T gate (non-Clifford, requires magic state). -/
| LT (q : Nat)
/-- Logical CNOT (Clifford). -/
| LCNOT (ctrl tgt : Nat)
/-- Logical CCZ (non-Clifford, requires |CCZ⟩ magic state). -/
| LCCZ (q1 q2 q3 : Nat)
/-- Logical CCX (Toffoli) = H_q3; CCZ q1 q2 q3; H_q3 in
surface-code FT. -/
| LCCX (q1 q2 q3 : Nat)Kinds of logical gates the framework recognises. Each
corresponds to a well-known FT-quantum primitive. Extensible.
structureLogicalGate
structure LogicalGate
A scheduled logical gate. Carries:
`id` — unique identifier within the layout.
`kind` — the logical operation performed.
`begin_us` / `end_us` — when the logical gate is in flight.
`implementing_syscalls` — indices into the underlying
physical schedule that implement this logical gate
(e.g., for `LCCZ`, this is the list of CNOTs +
measurements + Pauli updates from the CCZ teleportation
pattern).
`factory_used` — for magic-state-consuming gates, which
Factory zone provided the resource.
structureLogicalLayout
structure LogicalLayout
A LogicalLayout: maps logical-qubit ids to physical-qubit ids,
and lists the logical-gate sequence with each gate's physical
implementation.
INVARIANT: the `logical_gates` are ordered by `begin_us`.
defphysical_of_logical
def physical_of_logical (layout : LogicalLayout) (l_id : Nat) : Option Nat
Look up the physical qubit hosting a given logical qubit.
defLogicalGateKind.targets
def LogicalGateKind.targets (k : LogicalGateKind) : List Nat
Logical qubits referenced by a logical gate's kind.
defassignments_cover_gates
def assignments_cover_gates (layout : LogicalLayout) : Bool
Is the LogicalLayout's qubit assignment consistent with the
set of logical qubits the gates reference? Every logical
qubit appearing in any gate target must have a physical
assignment in `l_to_p`.
defgate_indices_valid
def gate_indices_valid (lg : LogicalGate) (sched : Schedule) : Bool
Does a logical gate's implementing-syscall list reference
valid indices in the underlying schedule?
defall_gates_have_valid_indices
def all_gates_have_valid_indices (layout : LogicalLayout)
(sched : Schedule) : BoolFor every logical gate, its implementing syscalls reference
valid indices in the underlying schedule.
defgates_time_ordered
def gates_time_ordered (layout : LogicalLayout) : Bool
Logical gates are time-ordered (begin_us monotonically
increasing across the list).
defconsistent
def consistent (layout : LogicalLayout) (sched : Schedule) : Bool
*The headline consistency predicate.** A LogicalLayout is
consistent with an underlying physical schedule iff:
(i) every logical qubit referenced by a gate has a physical
assignment;
(ii) every implementing-syscall index is in range;
(iii) the logical gates are time-ordered.
Each check is decidable on concrete layouts.
structureLogicalStep
structure LogicalStep
A single logical operation, time-stamped. This is the
SOURCE level: no physical qubits, no transit, no decoder.
abbrevLogicalSchedule
abbrev LogicalSchedule
A logical schedule is a list of timed logical operations.
deffind_impl
def find_impl (layout : LogicalLayout) (step_id : Nat) : Option LogicalGate
Find the implementation of a logical step (by `step_id`) in
a `LogicalLayout`. Returns the matching `LogicalGate` if any.
defstep_implemented
def step_implemented (step : LogicalStep) (layout : LogicalLayout)
(psched : Schedule) : BoolBoolean check: a logical step is correctly implemented by
the layout + physical schedule iff:
(i) the layout has a LogicalGate with matching `step_id`;
(ii) the gate's kind matches the step's kind;
(iii) the gate's time interval matches the step's;
(iv) the gate's implementing-syscall indices are valid
positions in the physical schedule.
defphysical_implements_logical
def physical_implements_logical
(lsched : LogicalSchedule) (layout : LogicalLayout)
(psched : Schedule) : Bool*The headline two-level verification predicate.**
`physical_implements_logical lsched layout psched = true`
iff every logical step in the source `lsched` has a
correctly-matching implementation in the bridge `layout`
that references valid positions in the target `psched`.
This is STRUCTURAL correctness only. Full SEMANTIC
correctness — i.e., the target's quantum-mechanical action
equals the source's intended unitary — is NOT established
here; no module currently discharges it for `Schedule`.
Decidable on concrete schedules.
deffid_step
def fid_step (acc : Nat) (f_x1e6 : Nat) : Nat
Compose one factor of fidelity (in ppm) into the running total.
defschedule_fidelity_ppm
def schedule_fidelity_ppm (arch : Architecture) (sched : Schedule)
(f_1q_x1e6 f_2q_x1e6 f_meas_x1e6 : Nat) : NatTotal schedule fidelity in parts-per-million. Takes 1q/2q/Measure
gate fidelities as paper-cited inputs; channel fidelities come
from the architecture.
For TransitQubit, fidelity is applied TWICE (once for
`activate`, once for `deactivate`) to match ZAC's
per-rearrangeJob accounting.
defneutral_atom_mini
def neutral_atom_mini : Architecture
Neutral-atom mini-architecture. Values cited from:
`hardware_spec/toy_architecture.json` (ZAC): SLM grids,
atom_transfer = 15 µs, rydberg = 0.36 µs, 1qGate = 0.625 µs.
`simulator.py` defaults: fidelity_2q = 0.995,
fidelity_atom_transfer = 0.999, T = 1.5 × 10^6 µs.
Bluvstein 2024 (Nature 626, 58 (2024)): per-step atom-transfer
≈ 10 µs grounding the ZAC value.
The 30 / 60 µm zone diameters come from the toy 10×10 SLM grid
at 3 µm site spacing.
deftrapped_ion_mini
def trapped_ion_mini : Architecture
Trapped-ion mini-architecture. Values cited from:
Pino et al. 2021 Nature 592, 209 (Quantinuum H1 architecture):
ion shuttle through one junction ≈ 500 µs, shuttle fidelity
≈ 0.9994, 2-qubit MS gate ≈ 250 µs.
Trap-segment capacity ~30 ions per segment is representative
for the H1 / H2 series (cited in Pino § "Apparatus").
Ground-state coherence: T ≈ 1 sec (per Quantinuum
benchmark whitepapers; consistent with Pino's reported values).
defsuperconducting_mini
def superconducting_mini : Architecture
example(example)
example : verifies neutral_atom_mini []
example(example)
example : verifies trapped_ion_mini []
example(example)
example : verifies superconducting_mini []
example(example)
example :
(neutral_atom_mini.find_zone 0).map Zone.role = some ZoneRole.Memoryexample(example)
example :
(neutral_atom_mini.find_channel 1).map Channel.kind
= some ChannelKind.MagicSupplyexample(example)
example : superconducting_mini.t_coherence_us = 100
FormalRV.System.Core.CodedLayout
FormalRV/System/Core/CodedLayout.lean
FormalRV.System.Core.CodedLayout — code-block-aware logical
layout for QEC codes.
NAMESPACE NOTE: although this file lives under
`FormalRV/System/Core/`, it deliberately declares
`namespace FormalRV.System.Architecture` — it extends the
Architecture layer in place (`syscall_acts_on` operates on
`Architecture.SysCall`, and `CodedLogicalLayout` generalises
`Architecture.LogicalLayout`), so callers work in a single
namespace.
Supports declaring that a computation uses a specific QEC code
(e.g. `[[144, 18, 12]]`) and referencing logical qubits by
their local index within that code block.
Compared to `LogicalLayout` (which maps logical qubits 1-to-1
with physical atoms — the trivial code), this module supports:
A list of `CodeBlockBinding`s, each declaring an
`[[n, k, d]]` instance and the `n` physical atoms it
occupies.
`LogicalQubitBinding`s mapping a flat logical-qubit ID
to a `(block_id, local_index)` pair, where
`local_index < k`.
A consistency check that:
- every block's physical-qubit list has length n
- every binding references a valid block + valid
local index
- every gate target has a binding
Designed for any qLDPC family: bivariate-bicycle, lifted-product,
surface code (k=1), or any code described by a `QECCode`.
Consumed by `FormalRV.PPM.Syntax.PauliOps`
(`verify_logical_pauli_measurement`).
structureCodeBlockBinding
structure CodeBlockBinding
A `CodeBlockBinding` declares that a specific set of
physical qubits implements a particular QEC code instance.
`physical_qubits` lists the `code.n` physical-atom IDs in
the architecture that form this block.
structureLogicalQubitBinding
structure LogicalQubitBinding
A `LogicalQubitBinding` maps a flat logical-qubit ID (the
one used in `LogicalGateKind` targets) to a `(block_id,
local_index)` pair, where `local_index < code.k`.
Each logical qubit is BACKED BY many physical atoms (the
whole code block); the explicit qubit-to-physical
enumeration lives in `CodeBlockBinding.physical_qubits`.
structureCodedLogicalLayout
structure CodedLogicalLayout
A code-block-aware logical layout: a list of code blocks,
a list of logical-qubit bindings, and the ordered list of
logical gates. Generalises `LogicalLayout` to non-trivial
codes.
deffind_block
def find_block (clayout : CodedLogicalLayout) (bid : Nat) :
Option CodeBlockBindingFind a code block by `block_id`.
deffind_binding
def find_binding (clayout : CodedLogicalLayout) (lid : Nat) :
Option LogicalQubitBindingFind the binding for a logical-qubit ID.
defblocks_have_correct_size
def blocks_have_correct_size (clayout : CodedLogicalLayout) : Bool
Each code block's `physical_qubits` list has length equal
to the code's `n`.
defbindings_in_range
def bindings_in_range (clayout : CodedLogicalLayout) : Bool
Every logical-qubit binding references a valid block and a
`local_index` strictly less than that block's `k`.
defall_gate_targets_bound
def all_gate_targets_bound (clayout : CodedLogicalLayout) : Bool
Every logical qubit referenced by any gate has a binding.
defconsistent
def consistent (clayout : CodedLogicalLayout) : Bool
*The coded-layout consistency predicate.**
A `CodedLogicalLayout` is consistent iff:
(i) every block's physical-qubit list has the right size;
(ii) every binding's `local_index < k`;
(iii) every gate target has a binding.
Decidable on concrete layouts.
defsyscall_acts_on
def syscall_acts_on (sc : SysCall) : List Nat
Extract the list of physical-qubit IDs a SysCall touches.
Classical SysCalls (decoder, Pauli updates, magic requests)
return `[]`; an ancilla request names its exact site and the
reset OCCUPIES that qubit for the request's interval.
defallowed_atoms_for_logicals
def allowed_atoms_for_logicals
(clayout : CodedLogicalLayout) (logical_ids : List Nat) : List NatThe physical atoms allowed to be touched by a logical gate
targeting the given list of logical qubits. Equals the
UNION of the `physical_qubits` lists of those qubits' blocks.
defgate_impl_in_scope
def gate_impl_in_scope (clayout : CodedLogicalLayout)
(lg : LogicalGate) (psched : Schedule) : BoolDoes the impl-syscall list of a logical gate act only on
physical atoms allowed by the layout (i.e., atoms in the
union of the gate's targets' code blocks)?
defimpls_in_scope
def impls_in_scope (clayout : CodedLogicalLayout) (psched : Schedule) : Bool
*`impls_in_scope` headline predicate.** Every logical gate's
implementing syscalls act ONLY on atoms in the gate's
targets' code blocks.
Closes the gap between "impl indices are in range" (which the
bridge already checks) and "the impl syscalls act on the
right physical qubits".
defgate_impl_in_time_window
def gate_impl_in_time_window (lg : LogicalGate) (psched : Schedule) : Bool
Every impl syscall of a logical gate fires within the gate's
declared [begin_us, end_us] window. Otherwise the implementer
could claim a logical gate at time [100, 200] while the impl
syscalls actually fire at time 500 — temporal scope cheat.
defimpls_time_consistent
def impls_time_consistent (clayout : CodedLogicalLayout)
(psched : Schedule) : Bool*`impls_time_consistent` headline predicate.** Every logical
gate's implementing syscalls fire within the gate's time
window.
FormalRV.System.Core.ScheduleCombinators
FormalRV/System/Core/ScheduleCombinators.lean
FormalRV.System.Core.ScheduleCombinators — pure combinators over
`List SysCall` schedules: `scheduleWallclockUs` (foldl max end_us),
`shiftSysCall` / `shiftSchedule` (time translation), `seqSchedules` /
`parSchedules` and their n-ary forms `seqManySchedules` /
`parManySchedules`, with length and derived-wallclock lemmas.
Extracted verbatim from `Compile/LatticeSurgeryPPMContract.lean` §16.
Declarations stay in `namespace FormalRV.System.LatticeSurgeryPPMContract`
to preserve fully-qualified names. Depends only on `Core.Architecture`
(for `SysCall`). No Mathlib.
abbrevscheduleWallclockUs
abbrev scheduleWallclockUs : List SysCall → Nat
Wallclock of a schedule = max `end_us` across all SysCalls — an
alias for THE canonical counter (`Resource/SysCallCount.wallclockUs`);
resource claims must never redefine their own walk.
defshiftSysCall
def shiftSysCall (dt : Nat) (sc : SysCall) : SysCall
Shift a single SysCall forward in time by `dt` µs.
defshiftSchedule
def shiftSchedule (dt : Nat) (xs : List SysCall) : List SysCall
Shift every SysCall in a schedule forward by `dt` µs.
defseqSchedules
def seqSchedules (xs ys : List SysCall) : List SysCall
Sequential composition: `xs ` followed by `ys` shifted by
`wallclock(xs)`. After the merge, `ys`'s SysCalls all begin
at or after `xs`'s wallclock.
defparSchedules
def parSchedules (xs ys : List SysCall) : List SysCall
Parallel composition: `xs` and `ys` both starting at their
original times. No time shift is applied; the merged
schedule's validity must be RECHECKED (e.g., for ancilla
aliasing or factory-port conflicts).
theoremshiftSchedule_length
theorem shiftSchedule_length (dt : Nat) (xs : List SysCall) :
(shiftSchedule dt xs).length = xs.lengththeoremseqSchedules_length
theorem seqSchedules_length (xs ys : List SysCall) :
(seqSchedules xs ys).length = xs.length + ys.lengththeoremparSchedules_length
theorem parSchedules_length (xs ys : List SysCall) :
(parSchedules xs ys).length = xs.length + ys.lengththeoremseqSchedules_wallclock_is_derived
theorem seqSchedules_wallclock_is_derived (xs ys : List SysCall) :
scheduleWallclockUs (seqSchedules xs ys)
= (seqSchedules xs ys).foldl (fun acc sc => Nat.max acc sc.end_us) 0*Anti-spreadsheet (`rfl`)**: the wallclock of `seqSchedules`
IS the foldl over the merged list — not a closed-form sum.
theoremparSchedules_wallclock_is_derived
theorem parSchedules_wallclock_is_derived (xs ys : List SysCall) :
scheduleWallclockUs (parSchedules xs ys)
= (parSchedules xs ys).foldl (fun acc sc => Nat.max acc sc.end_us) 0*Anti-spreadsheet (`rfl`)**: same for `parSchedules`.
defseqManySchedules
def seqManySchedules : List (List SysCall) → List SysCall | [] => [] | xs :: rest => seqSchedules xs (seqManySchedules rest)
Sequential composition of many schedules, recursively shifted.
defparManySchedules
def parManySchedules : List (List SysCall) → List SysCall | [] => [] | xs :: rest => parSchedules xs (parManySchedules rest)
Parallel composition of many schedules, all starting at t=0.
theoremseqManySchedules_singleton
theorem seqManySchedules_singleton (xs : List SysCall) :
seqManySchedules [xs] = xsSingleton case for `seqManySchedules`: equals the input
(shifted by 0, since the empty tail has wallclock 0).
theoremparManySchedules_singleton
theorem parManySchedules_singleton (xs : List SysCall) :
parManySchedules [xs] = xsSingleton case for `parManySchedules`: equals the input.
FormalRV.System.Decoder.DecodeLatencySensitivity
FormalRV/System/Decoder/DecodeLatencySensitivity.lean
FormalRV.System.DecodeLatencySensitivity — the decode latency as a first-class
USER-SPECIFIED input that flows into the verified runtime (not a buried
constant), coupled to the decoder provisioning it also drives:
• `reactionLimitedModel decodeLatency` — a cost model whose `tauToff` IS the
decode latency (in cycles), so the verified `estimateWith` time is
`n_toff · decodeLatency · cycle`;
• MONOTONICITY: a slower decoder ⇒ a larger verified runtime;
• a SENSITIVITY table for RSA-2048 (latency 10/20/27/40 µs →
7.5/15/20.25/30 h), with the crossover at latency = d, where
reaction-limited meets the d-cycle ceiling;
• COUPLING: the SAME decode-latency input also scales the decoder LANE
requirement (`patches · decodeLatency`, `DecoderBacklogModel`), so a
slower decoder costs BOTH time and classical hardware.
No `sorry`, no new `axiom`.
defreactionLimitedModel
def reactionLimitedModel (decodeLatencyCycles factory : Nat) : CostModel
*Reaction-limited cost model.** The logical-Toffoli cost `tauToff` is the
DECODE LATENCY (in code cycles) — a USER-SPECIFIED input — not the code
distance `d`. Everything else mirrors `surfaceModel`.
theoremreactionLimited_time
theorem reactionLimited_time (decodeLatencyCycles factory : Nat)
(hw : Hardware) (w : Workload) (c : QECCode) (ow p : Nat) :
(estimateWith (reactionLimitedModel decodeLatencyCycles factory) hw w c ow p).time_us_tenths
= w.n_toff * decodeLatencyCycles * hw.cycle_time_us_tenths*The decode latency FLOWS INTO the verified time.** Through the rfl-proven
`estimateWith` framework, the runtime is `n_toff · decodeLatency · cycle` — a
function of the user's decode-latency input.
theoremtime_mono_decodeLatency
theorem time_mono_decodeLatency (L L' factory : Nat)
(hw : Hardware) (w : Workload) (c : QECCode) (ow p : Nat) (h : L ≤ L') :
(estimateWith (reactionLimitedModel L factory) hw w c ow p).time_us_tenths
≤ (estimateWith (reactionLimitedModel L' factory) hw w c ow p).time_us_tenths*MONOTONE in the decode latency.** A slower decoder (larger latency) gives a
larger verified runtime, all else equal — so the latency genuinely affects the
verified time (it is not inert).
defrsa2048_runtime
def rsa2048_runtime (L : Nat) : Nat
RSA-2048 verified runtime (tenths-µs) at decode latency `L` cycles.
theoremrsa2048_runtime_eq
theorem rsa2048_runtime_eq (L : Nat) :
(estimateWith (reactionLimitedModel L 0) { cycle_time_us_tenthstheoremrsa2048_at_10
theorem rsa2048_at_10 : rsa2048_runtime 10 = 270_000_000_000
10 µs decoder ⇒ 7.5 h (= 270×10⁹ tenths-µs).
theoremrsa2048_at_20
theorem rsa2048_at_20 : rsa2048_runtime 20 = 540_000_000_000
20 µs decoder ⇒ 15 h — DOUBLING the decode latency DOUBLES the runtime.
theoremrsa2048_at_27
theorem rsa2048_at_27 : rsa2048_runtime 27 = 729_000_000_000
Decode latency = d = 27 cycles ⇒ 20.25 h — reaction-limited meets the d-cycle
ceiling (the crossover: a decoder this slow gives no pipelining benefit).
theoremrsa2048_at_40
theorem rsa2048_at_40 : rsa2048_runtime 40 = 1_080_000_000_000
40 µs decoder ⇒ 30 h — past the crossover the decoder DOMINATES the runtime.
theoremcrossover_at_distance
theorem crossover_at_distance :
rsa2048_runtime 27 = ReactionLimitedRuntime.dCycleRuntime 2_700_000_000 27 10The crossover is at latency = code distance: there the verified reaction-limited
runtime equals the d-cycle ceiling (`ReactionLimitedRuntime.rsa2048_dcycle`).
theoremcoupling_10
theorem coupling_10 :
rsa2048_runtime 10 = 270_000_000_000
∧ arrivalsPerWindow 6200 10 = 62_000At 10 µs: runtime 7.5 h AND 62 000 decode lanes.
theoremcoupling_20
theorem coupling_20 :
rsa2048_runtime 20 = 540_000_000_000
∧ arrivalsPerWindow 6200 20 = 124_000At 20 µs: runtime 15 h AND 124 000 lanes — doubling the latency doubles BOTH.
theoremdecode_latency_drives_time_and_lanes
theorem decode_latency_drives_time_and_lanes
(L p factory : Nat) (hw : Hardware) (w : Workload) (c : QECCode) (ow pp : Nat) :
(estimateWith (reactionLimitedModel L factory) hw w c ow pp).time_us_tenths
= w.n_toff * L * hw.cycle_time_us_tenths
∧ arrivalsPerWindow p L = p * LThe two linear effects packaged parametrically. DEFINITIONAL content: this
is just the conjunction of `reactionLimited_time` with the unfolding of
`arrivalsPerWindow` — for any decode latency `L` and patch count `p`, the
runtime is `n_toff·L·cycle` and the backlog-free lane threshold is `p·L`.
FormalRV.System.Decoder.DecoderBacklogModel
FormalRV/System/Decoder/DecoderBacklogModel.lean
FormalRV.System.DecoderBacklogModel — a parametric model of the decoder
throughput / backlog gap. Where `ResourceAuditGaps.decoderThroughputInv` is a
one-shot `load ≤ lanes` check, this module models the QUEUE DYNAMICS over time
and proves the dichotomy:
• PROVISIONED (lanes ≥ load): the syndrome backlog is ZERO for ALL time —
reaction-limited execution is sound, the 7.5 h runtime stands.
• UNDER-PROVISIONED (lanes < load): the backlog grows WITHOUT BOUND (linear in
time, Fowler/Terhal) — the effective reaction time diverges, so NO fixed
runtime bound (8 h, 20.25 h, anything) holds. The classical decoder is then
the binding constraint, not the qubits.
Parametric in (patches, decodeLatency, lanes, windows). GE2021 instantiated.
Independently reproduced by the FTQ-VM (see `System/VM_AUDIT.md`).
No Mathlib beyond Nat/omega. No `sorry`, no `axiom`.
defarrivalsPerWindow
def arrivalsPerWindow (patches decodeLatency : Nat) : Nat
defservicesPerWindow
def servicesPerWindow (lanes : Nat) : Nat
defbacklogFree
def backlogFree (patches decodeLatency lanes : Nat) : Bool
Backlog-free iff each window's service ≥ its arrivals.
defbacklogGrowthPerWindow
def backlogGrowthPerWindow (patches decodeLatency lanes : Nat) : Nat
Net backlog added per window (Nat-saturating; 0 when backlog-free).
defbacklogAfter
def backlogAfter (k patches decodeLatency lanes : Nat) : Nat
Total syndrome backlog after `k` windows = `k · growth`.
theoremprovisioned_no_backlog
theorem provisioned_no_backlog (k patches decodeLatency lanes : Nat)
(h : backlogFree patches decodeLatency lanes = true) :
backlogAfter k patches decodeLatency lanes = 0*Provisioned ⇒ ZERO backlog for ALL time.** If lanes meet the load, the
syndrome queue never grows — reaction-limited execution is sound.
theoremunderprovisioned_unbounded_backlog
theorem underprovisioned_unbounded_backlog (patches decodeLatency lanes : Nat)
(h : backlogFree patches decodeLatency lanes = false) (bound : Nat) :
∃ k, bound < backlogAfter k patches decodeLatency lanes*Under-provisioned ⇒ backlog grows WITHOUT BOUND.** If lanes fall short, then
for ANY bound there is a time `k` whose backlog exceeds it — the queue diverges
(linear-in-time), so no fixed runtime can hold.
defoutstandingWork
def outstandingWork (k patches decodeLatency lanes : Nat) : Nat
Effective decode work outstanding after `k` windows (in syndrome-units): the
standing service capacity plus the accumulated backlog.
theoremunderprovisioned_work_diverges
theorem underprovisioned_work_diverges (patches decodeLatency lanes : Nat)
(h : backlogFree patches decodeLatency lanes = false) (bound : Nat) :
∃ k, bound < outstandingWork k patches decodeLatency lanesUnder-provisioned, the outstanding decode work diverges — the reaction time
cannot stay at its 10 µs design point, so the reaction-limited 7.5 h (and even
the 20.25 h d-cycle ceiling) is not a valid runtime bound.
theoremge2021_provisioned_62000
theorem ge2021_provisioned_62000 (k : Nat) : backlogAfter k 6200 10 62000 = 0
With 62 000 decode lanes the GE2021 decoder is provisioned: zero backlog ∀ time
— reaction-limited 7.5 h is sound.
theoremge2021_underprovisioned_6200
theorem ge2021_underprovisioned_6200 (bound : Nat) :
∃ k, bound < backlogAfter k 6200 10 6200With only one lane per patch (6200, un-pipelined) the decoder is
UNDER-provisioned, and the backlog diverges — RSA-2048 does NOT finish in any
fixed time on that decoder fabric (the decoder is binding, not the 20 M qubits).
theoremge2021_threshold
theorem ge2021_threshold : arrivalsPerWindow 6200 10 = 62_000
The provisioning threshold is exactly `patches · decodeLatency` decode lanes:
62 000 for GE2021. Below it, divergence; at or above, soundness.
FormalRV.System.Decoder.ReactionLimitedRuntime
FormalRV/System/Decoder/ReactionLimitedRuntime.lean
FormalRV.System.ReactionLimitedRuntime — d-cycle vs reaction-limited runtime.
`surfaceModel.tauToff = d` charges `d` code cycles (27 µs at d=27, 1 µs cycle)
per logical Toffoli, sequentially. GE2021 instead runs REACTION-LIMITED
(notes/gidney-ekera-2021.md; paper §"reaction time 10 µs"): the next Toffoli
starts after one decode + feed-forward reaction time (10 µs), not after `d`
full cycles. For RSA-2048 (2.7×10⁹ Toffolis):
d-cycle (ours) : 2.7×10⁹ · 27 µs = 72 900 s = 20.25 h (our ceiling)
reaction-limited (GE) : 2.7×10⁹ · 10 µs = 27 000 s = 7.5 h (≈ GE2021 7.4 h)
So the "2.5× gap" between our ceiling and GE2021's figure is EXACTLY the
27 µs / 10 µs cost-model ratio (`gap_is_dcycle_vs_reaction`) — no unexplained
algorithmic speed-up.
Residual assumption: reaction-limited execution requires the classical decoder
to return within ONE reaction time for every patch, every step — a real-time
load of `realtimeDecodeLoad` ≈ 6.2×10⁹ decode-tasks/s, a CLASSICAL resource
outside the 20 M qubit budget. If decoding falls behind, the reaction time
grows (Fowler/Terhal backlog) and the runtime degrades toward — or past — the
d-cycle ceiling. The queue dynamics and the provisioned/divergent dichotomy
are proved in `DecoderBacklogModel`.
No `sorry`, no new `axiom`.
defreactionTime_tenthsUs
def reactionTime_tenthsUs : Nat
GE2021 reaction time: 10 µs = 100 tenths-µs (paper §2.13).
defreactionLimitedRuntime
def reactionLimitedRuntime (toffoliDepth : Nat) : Nat
REACTION-LIMITED runtime = (sequential Toffoli depth) × reaction time.
defdCycleRuntime
def dCycleRuntime (toffoli d cycle_tenthsUs : Nat) : Nat
d-CYCLE runtime (our `surfaceModel`) = (Toffoli count) × d × cycle time.
theoremrsa2048_dcycle
theorem rsa2048_dcycle : dCycleRuntime 2_700_000_000 27 10 = 729_000_000_000
Our d-cycle ceiling: 20.25 h (729×10⁹ tenths-µs).
theoremrsa2048_reaction_limited
theorem rsa2048_reaction_limited : reactionLimitedRuntime 2_700_000_000 = 270_000_000_000
The reaction-limited runtime: 7.5 h (270×10⁹ tenths-µs) — matching GE2021's
~7.4 h reported figure.
theoremgap_is_dcycle_vs_reaction
theorem gap_is_dcycle_vs_reaction :
2 * reactionLimitedRuntime 2_700_000_000 ≤ dCycleRuntime 2_700_000_000 27 10
∧ dCycleRuntime 2_700_000_000 27 10 ≤ 3 * reactionLimitedRuntime 2_700_000_000*The "2.5× gap" is the d-cycle (27 µs) vs reaction-time (10 µs) ratio**, not
an unexplained optimisation: our ceiling is between 2× and 3× the reaction-
limited runtime that reproduces GE2021.
defrsa2048_patches
def rsa2048_patches : Nat
RSA-2048 live logical patches (≈ data-block logical qubits).
defsyndromeRoundsPerSec
def syndromeRoundsPerSec : Nat
Syndrome rounds per second per patch (1 µs cycle ⇒ 10⁶/s).
defrealtimeDecodeLoad
def realtimeDecodeLoad : Nat
*Real-time decoding load**: patches × rounds/s = the number of decode tasks
per second the classical decoder fabric must sustain to keep the reaction time
at 10 µs. 6.2×10⁹ decode-tasks/s — a CLASSICAL resource NOT in the 20 M qubit
budget and NOT bounded by our `decoderInv`.
theoremrealtimeDecodeLoad_value
theorem realtimeDecodeLoad_value : realtimeDecodeLoad = 6_200_000_000
theoremreaction_limited_assumes_decoder
theorem reaction_limited_assumes_decoder (toffoli : Nat) :
reactionLimitedRuntime toffoli = toffoli * reactionTime_tenthsUsDefinitional restatement (`rfl`) of `reactionLimitedRuntime`, kept as the
NAMED marker of the modelling assumption: the 7.5 h figure charges exactly
one reaction time per Toffoli, which presumes the decoder sustains
`realtimeDecodeLoad`. This is a documentation-level claim, not verified
content — the actual decoder condition is proved in `DecoderBacklogModel`
(provisioned ⇒ zero backlog; under-provisioned ⇒ divergence).
FormalRV.System.Decoder.ResourceAuditGaps
FormalRV/System/Decoder/ResourceAuditGaps.lean
FormalRV.System.ResourceAuditGaps — uncounted-cost findings from the resource
self-audit. The audit found no hidden fudge factor (`ReactionLimitedRuntime`
proves the 2.5× time gap is exactly the 27 µs/10 µs cost-model ratio); the
residual risk is OMISSION. The checkable parts are encoded as theorems, the
rest is recorded honestly as documentation:
GAP 1 decoder THROUGHPUT — the missing `load ≤ lanes` invariant (encoded
here as `decoderThroughputInv`; full queue dynamics with the
provisioned/divergent dichotomy in `DecoderBacklogModel`).
GAP 2 the reported runtime is ~100× above the critical-path depth floor,
so GE2021 runs reaction-limited at the Toffoli COUNT, not the DEPTH;
code-depth-limited (serial) lookups push the 7.5 h past 8 h (encoded
as inequalities).
GAP 3 magic-state factory undersize (~17×) and per-state delivery
transport (~d cycles each) — documentation-level findings only, see
the GAP 3 section.
No `sorry`, no new `axiom`.
defdecoderThroughputOk
def decoderThroughputOk (patches decodeLatencyCycles nLanes : Nat) : Bool
Worst-case decode lanes required: `patches · decodeLatencyCycles` (each patch's
per-cycle syndrome occupies a lane for the full decode latency). Streaming/
pipelined decoders reduce this to `patches`.
defdecoderThroughputInv
def decoderThroughputInv (patches decodeLatencyCycles nLanes : Nat) : SpaceTimeInvariant
The decoder-throughput SpaceTimeInvariant — composes into `checkAll` like any
other system constraint. `nLanes` is a CLASSICAL co-processor count, NOT a
qubit: the decoder fabric this invariant constrains is absent from the 20 M
physical-qubit budget entirely.
theoremge2021_decode_lanes_worstcase
theorem ge2021_decode_lanes_worstcase : 6200 * 10 = 62_000
GE2021: 6200 patches, 10-cycle (10 µs) decode latency ⇒ worst-case **62 000
parallel decode lanes** to avoid backlog.
theoremge2021_decoder_oneper_patch_fails
theorem ge2021_decoder_oneper_patch_fails :
decoderThroughputOk 6200 10 6200 = falseA machine with only one decoder lane PER PATCH (6200, un-pipelined) is
UNDER-PROVISIONED — backlog grows.
theoremge2021_decoder_provisioned_ok
theorem ge2021_decoder_provisioned_ok :
decoderThroughputOk 6200 10 62_000 = true62 000 lanes (or fully-pipelined streaming decoders) suffice.
defmodexpDepthFloorCycles
def modexpDepthFloorCycles : Nat
modexp critical-path depth × ~40 cycles/Toffoli = 247.7 M cycles ≈ 4.1 min.
theoremmodexpDepthFloor_value
theorem modexpDepthFloor_value : modexpDepthFloorCycles = 247_726_080
theoremruntime_is_100x_depth_floor
theorem runtime_is_100x_depth_floor :
100 * modexpDepthFloorCycles ≤ 27_000_000_000GE2021's reaction-limited runtime (7.5 h = 27×10⁹ cycles at 1 µs) is ≥ 100× the
critical-path depth floor — the computation is run NEAR-SEQUENTIALLY, leaving
a ~100× space-time parallelism headroom (and hiding any serial-lookup residue).
theoremmixed_cost_pushes_above_8h
theorem mixed_cost_pushes_above_8h :
28_800_000_000 < (85 * 10 + 15 * 27) * 27_000_000If a fraction of Toffolis are code-depth-limited (lookups at 27 µs, not 10 µs),
the reaction-limited 7.5 h is optimistic. Worked (in µs): 15 % depth-limited
gives per-op average 0.85·10 + 0.15·27 = 12.55 µs, so runtime = 12.55 µs ×
2.7×10⁹ = 33.9×10⁹ µs ≈ 9.4 h — ABOVE the reported 8 h = 28.8×10⁹ µs.
FormalRV.System.Decoder.SyndromeMeasurementLatency
FormalRV/System/Decoder/SyndromeMeasurementLatency.lean
FormalRV.System.SyndromeMeasurementLatency — syndrome-extraction overhead made
explicit and HARDWARE-LATENCY-DRIVEN:
(1) the surface-code CYCLE time is built from gate/measure/reset latencies
(one syndrome round = `gateLayers` CNOT layers + measure + reset), so the
qubit-measurement latency `tMeasure` flows into the verified runtime,
monotonically — with an RSA-2048 sensitivity table;
(2) every `[[n,1,d]]` patch carries one syndrome-measure ancilla per
stabilizer (`n − 1`), and extraction is ALWAYS-ON: every patch measures
all its stabilizers every code cycle for the whole computation, so the
physical syndrome-measurement workload scales with
(all logical qubits) × (total cycles), not with active operations.
No `sorry`, no new `axiom`.
defsurfaceCycleTime
def surfaceCycleTime (tGate tMeasure tReset gateLayers : Nat) : Nat
Surface-code cycle time (tenths-µs) from hardware latencies. Standard surface
syndrome round: 4 CNOT layers + measure + reset.
defhwOfLatencies
def hwOfLatencies (tGate tMeasure tReset gateLayers : Nat) : Hardware
Hardware whose cycle time is the latency-built surface cycle.
theoremruntime_with_measurement_latency
theorem runtime_with_measurement_latency
(T L factory d tGate tMeasure tReset gateLayers ow p : Nat) :
(estimateWith (surfaceModel factory) (hwOfLatencies tGate tMeasure tReset gateLayers)
(shorWorkload T L) (surfaceCodeD d) ow p).time_us_tenths
= T * d * surfaceCycleTime tGate tMeasure tReset gateLayers*Runtime as a function of `tMeasure`.** Through the rfl-verified `estimateWith`,
the surface-code Shor runtime is `n_toff · d · (gateLayers·tGate + tMeasure +
tReset)` — so the qubit-measurement latency is a live input to the verified time.
theoremtime_mono_measurementLatency
theorem time_mono_measurementLatency
(T L factory d tGate tM tM' tReset gateLayers ow p : Nat) (h : tM ≤ tM') :
(estimateWith (surfaceModel factory) (hwOfLatencies tGate tM tReset gateLayers)
(shorWorkload T L) (surfaceCodeD d) ow p).time_us_tenths
≤ (estimateWith (surfaceModel factory) (hwOfLatencies tGate tM' tReset gateLayers)
(shorWorkload T L) (surfaceCodeD d) ow p).time_us_tenths*MONOTONE in the measurement latency**: a slower qubit measurement gives a
strictly larger verified runtime (all else fixed) — it is not inert.
defrsa2048_time_at_tMeasure
def rsa2048_time_at_tMeasure (tMeasure : Nat) : Nat
theoremrsa2048_tM_5
theorem rsa2048_tM_5 : rsa2048_time_at_tMeasure 5 = 729_000_000_000
tMeasure = 5 (0.5 µs): cycle = 10 tenths-µs (1 µs) → 20.25 h.
theoremrsa2048_tM_15
theorem rsa2048_tM_15 : rsa2048_time_at_tMeasure 15 = 1_458_000_000_000
tMeasure = 15 (1.5 µs): cycle = 20 → 40.5 h — a slower measurement DOUBLES the
cycle and the runtime.
theoremrsa2048_tM_35
theorem rsa2048_tM_35 : rsa2048_time_at_tMeasure 35 = 2_916_000_000_000
tMeasure = 35 (3.5 µs, slow readout): cycle = 40 → 81 h.
theoremmeasurement_latency_changes_time
theorem measurement_latency_changes_time :
rsa2048_time_at_tMeasure 5 ≠ rsa2048_time_at_tMeasure 15*Changing the qubit-measurement latency changes the verified time** — the
framework is not measurement-latency-blind.
defsyndromeAncillaPerPatch
def syndromeAncillaPerPatch (d : Nat) : Nat
Syndrome-measure ancilla per `[[n,1,d]]` surface patch: one per stabilizer,
`n − 1` (both bases). For the d=27 patch (n=1405): 1404 ancilla.
theoremsyndromeAncilla_d27
theorem syndromeAncilla_d27 : syndromeAncillaPerPatch 27 = 1404
deftotalSyndromeRounds
def totalSyndromeRounds (nToff d : Nat) : Nat
Total syndrome rounds over the whole computation = total code cycles = the
runtime in cycles = `n_toff · d` (one logical Toffoli = d rounds).
deftotalPhysicalSyndromeMeas
def totalPhysicalSyndromeMeas (nLogical d nToff : Nat) : Nat
*Always-on physical syndrome measurements**: EVERY logical patch measures ALL
its stabilizers EVERY round for the whole duration — `n_logical · (n−1) ·
(n_toff · d)`. This is the physical measurement workload, vastly larger than
the `412×10⁹` LOGICAL measurements. Note the model has NO idle/active
distinction — by construction each patch contributes the same per-patch term
`(n−1)·(n_toff·d)` whether or not any of the global Toffolis touch it, i.e.
idle qubits are not free: they pay full-duration extraction.
theoremsyndrome_overhead_scales_with_all_qubits
theorem syndrome_overhead_scales_with_all_qubits (d nToff a b : Nat) (h : a ≤ b) :
totalPhysicalSyndromeMeas a d nToff ≤ totalPhysicalSyndromeMeas b d nToffThe always-on physical syndrome workload is LINEAR in the logical-qubit count —
so the 6200 idle+active patches each pay the full-duration extraction cost
(this is exactly the decoder load of `DecoderBacklogModel`, now tied to the
physical measurement count).
FormalRV.System.DeviceLane.DependencyGraph
FormalRV/System/DeviceLane/DependencyGraph.lean
FormalRV.System.DependencyGraph — a first-class CAUSAL-DEPENDENCY graph for
parallel schedules: the (B) half of "max parallelism subject to invariants".
The system invariants are about two things — (A) RESOURCE conflict-freedom and
(B) CAUSAL dependencies. (A) is captured by the `checkAll` resource invariants
(capacity, exclusivity, throughput, decoder). This file gives (B) the same
first-class treatment: an explicit DEPENDENCY GRAPH over a schedule, a decidable
check that the schedule RESPECTS it, and a wrapping into the SAME extensible
`SpaceTimeInvariant` framework, so causality is verified by the same mechanism
as the resource constraints. Then "two ops may run concurrently iff no
resource conflict (A) AND no causal dependency (B)" is one uniform `checkAll`.
The causal orderings (qianxu App. E, all class (B)): sub-circuits C_i are
sequential; within each, teleport-in → compute → teleport-out; each Toffoli is
a sequence of PPMs; measure → decode → feed-forward. These are producer→
consumer edges: the producer must FINISH before the consumer may START.
No Mathlib. Pure Bool / Nat + `decide`. No `sorry`, no `axiom`.
structureDepEdge
structure DepEdge
A causal dependency edge: the operation at schedule index `before` must
FINISH (its `end_us`) before the operation at index `after` may START (its
`begin_us`). This is a producer → consumer edge.
structureDepGraph
structure DepGraph
A causal dependency graph over a schedule: a list of producer → consumer
edges. (The schedule it refers to is supplied separately, as a `List
SysCall`; edges are indices into it.)
defrespectsCausality
def respectsCausality (sched : List SysCall) (g : DepGraph) : Bool
A schedule RESPECTS a dependency graph iff every edge's producer finishes no
later than its consumer starts. A dangling edge (index out of range) marks a
malformed program → rejected.
*WARNING — index-based, not identity-based.** Edges refer to POSITIONS in the
`sched` list, not to operation ids. Reordering the list changes which
operations each edge constrains, so the same `DepGraph` means something
different on a permuted schedule. Pair each graph with one fixed schedule
ordering (as the examples below do); an id-based semantic fix is out of scope
here (cf. `DeviceSchedule.depsRespected`, which is id-based but assumes unique
ids).
defcausalityInv
def causalityInv (g : DepGraph) : SpaceTimeInvariant
theoremno_self_dependency
theorem no_self_dependency (sched : List SysCall) (g : DepGraph)
(h : respectsCausality sched g = true)
(e : DepEdge) (he : e ∈ g.edges) (heq : e.before = e.after)
(u : SysCall) (hu : sched[e.before]? = some u) (hpos : u.begin_us < u.end_us) :
FalsedeftoffoliSched
def toffoliSched : List SysCall
deftoffoliDeps
def toffoliDeps : DepGraph
example(example)
example : respectsCausality toffoliSched toffoliDeps = true
The time-ordered schedule respects every causal edge.
defbadToffoliSched
def badToffoliSched : List SysCall
A schedule that puts the feed-forward (index 4) BEFORE the decode (index 3)
violates the `3 → 4` edge — rejected. No parallelism can let a correction
precede the decode that produces it.
example(example)
example : respectsCausality badToffoliSched toffoliDeps = false
deftoffoliCtx
def toffoliCtx : SystemCtx
example(example)
example : checkAll (baseInvariants ++ [causalityInv toffoliDeps]) toffoliCtx = true
Resource (A) AND causal (B) together: the well-ordered Toffoli schedule
passes the unified check.
defbadToffoliCtx
def badToffoliCtx : SystemCtx
example(example)
example : checkAll (baseInvariants ++ [causalityInv toffoliDeps]) badToffoliCtx = false
The reordered schedule fails the unified check…
example(example)
example : checkAll baseInvariants badToffoliCtx = true
…because it violates CAUSALITY (B) specifically — the RESOURCE invariants (A)
still hold on it. Adding causality did not disturb the resource checks.
example(example)
example : (causalityInv toffoliDeps).check badToffoliCtx = false
theoremcausal_chain_floor
theorem causal_chain_floor (sched : List SysCall) (g : DepGraph)
(h : respectsCausality sched g = true)
(e1 e2 : DepEdge) (h1 : e1 ∈ g.edges) (h2 : e2 ∈ g.edges)
(hmid : e1.after = e2.before)
(u v w : SysCall)
(hu : sched[e1.before]? = some u) (hv : sched[e1.after]? = some v)
(hw : sched[e2.after]? = some w)
(hvpos : v.begin_us ≤ v.end_us) :
u.end_us ≤ w.begin_usdefchainMinTotal
def chainMinTotal : List (SysCall × Nat) → Nat | [] => 0 | (_, d) :: rest => d + chainMinTotal rest
deflastEnd
def lastEnd : List (SysCall × Nat) → Nat | [] => 0 | [(op, _)] => op.end_us | _ :: rest => lastEnd rest
`end_us` of the last operation in a chain (0 on the empty chain).
defMinChain
def MinChain : List (SysCall × Nat) → Prop
| [] => True
| [(op, d)] => op.begin_us + d ≤ op.end_us
| (op1, d1) :: (op2, d2) :: r =>
op1.begin_us + d1 ≤ op1.end_us ∧ op1.end_us ≤ op2.begin_us
∧ MinChain ((op2, d2) :: r)A chain is a valid execution iff each op runs at least its minimum duration
(`begin + dmin ≤ end`) and consecutive ops are dependency-linked
(`prev.end ≤ next.begin`). This holds of ANY schedule of the chain — it is
the `∀`-schedules hypothesis.
theoremcritical_path_lower_bound
theorem critical_path_lower_bound :
∀ (op0 : SysCall) (d0 : Nat) (rest : List (SysCall × Nat)),
MinChain ((op0, d0) :: rest) →
op0.begin_us + chainMinTotal ((op0, d0) :: rest)
≤ lastEnd ((op0, d0) :: rest)
| op0, d0, [], h =>THE CRITICAL-PATH LOWER BOUND. For ANY schedule (any begin/end times) of a
dependency chain `(op0, d0) :: rest` that respects the dependencies and runs
each op for at least its minimum duration, the last operation cannot finish
before `op0.begin + Σ dmin`. Equivalently: the makespan from `op0`'s start
to the chain's end is ≥ the sum of minimum durations — NO scheduling beats
the critical path. Proven by induction on the chain.
theoremcritical_path_two
theorem critical_path_two (op0 op1 : SysCall) (d0 d1 : Nat)
(hmin0 : op0.begin_us + d0 ≤ op0.end_us)
(hdep : op0.end_us ≤ op1.begin_us)
(hmin1 : op1.begin_us + d1 ≤ op1.end_us) :
op0.begin_us + (d0 + d1) ≤ op1.end_usThe two-operation seed, for clarity: along a single dependency edge
`op0 → op1`, every schedule has makespan ≥ `d0 + d1`. (One `omega`; this is
the base mechanism the induction iterates.)
theoremserial_chain_depth
theorem serial_chain_depth (τ : Nat) (begin_ : Nat → Nat)
(hdep : ∀ i, begin_ i + τ ≤ begin_ (i + 1)) (n : Nat) :
begin_ 0 + n * τ ≤ begin_ nPARAMETRIC CRITICAL-PATH LOWER BOUND. For a chain of gates where each gate
runs at least `τ` and gate `i+1` cannot start before gate `i`'s minimum
completion (`begin_ i + τ ≤ begin_ (i+1)`), gate `n` starts no earlier than
`begin_ 0 + n·τ` — for ANY start-time schedule `begin_`. Proven by induction
on `n`: NO graph algorithm, scalable to any depth.
example(example)
example (τ : Nat) (b : Nat → Nat) (h : ∀ i, b i + τ ≤ b (i + 1)) :
b 0 + 2048 * τ ≤ b 2048Instantiation at RSA-2048 scale is INSTANT — it is the `∀ n` theorem applied
to a literal, NOT a graph traversal. (n = 10⁹ would be equally immediate.)
So a depth-`n` dependency chain forces makespan ≥ `n·τ` at any scale, with no
per-instance graph computation.
defmodexpToffoliDepth
def modexpToffoliDepth (mults adds_per_mult adder_depth : Nat) : Nat
Modexp critical-path Toffoli-depth from its structural coefficients.
defruntimeFloorCycles
def runtimeFloorCycles (depth tau_toff_cycles : Nat) : Nat
Runtime floor in code-cycles = (critical-path Toffoli-depth) · (min cycles
per Toffoli).
theoremruntimeFloor_is_lower_bound
theorem runtimeFloor_is_lower_bound (τ : Nat) (begin_ : Nat → Nat)
(hdep : ∀ i, begin_ i + τ ≤ begin_ (i + 1)) (depth : Nat) :
begin_ 0 + runtimeFloorCycles depth τ ≤ begin_ depthTHE FLOOR IS A GENUINE `∀`-SCHEDULES LOWER BOUND. A critical path of `depth`
serially-dependent Toffolis, each taking at least `τ` cycles, takes at least
`runtimeFloorCycles depth τ` cycles — no matter the schedule and no matter
the resource provisioning (a specialisation of `serial_chain_depth`, with
`begin_ i` the start cycle of the i-th critical-path Toffoli).
FormalRV.System.DeviceLane.DeviceSchedule
FormalRV/System/DeviceLane/DeviceSchedule.lean
Part of the unified FT-scheduling framework — see `FormalRV.System.FTFramework` for the single
entry point. This is the `DeviceOp`/`DSchedule` validity checker (with placement evolution); its
`SysCall` sibling is `FormalRV.System.InvariantFramework` / `ScheduleInv.all_invariants_ok`. The
two are connected at the umbrella, not merged (the `SysCall`↔`DeviceOp` merge is deliberately
avoided to keep the concrete-schedule literals stable).
FormalRV.System.DeviceSchedule — an END-TO-END device-schedule execution engine and validity
checker for fault-tolerant quantum computation, built on the architecture-agnostic
`RoutingResourceModel` (which is proven consistent with Litinski surface-code lattice surgery
and with neutral-atom/ion transport).
This threads the routing/placement model into a RUNNING schedule and checks, together, the five
concerns a real FT machine must satisfy — the "tricky things":
1. **T-state preparation & scheduling** — `prepMagic` ops occupy a factory footprint for a
production duration.
2. **State teleportation (magic consumption)** — `consumeMagic` ops are surgery PPMs that
DEPEND on a completed `prepMagic` (the produce-before-consume WAIT), via `deps`.
3. **Decoder scheduling** — `decode` ops are bounded by the reaction time and limited by the
decoder count (queue depth).
4. **Space-time conflict avoidance** — no two time-overlapping ops share a footprint resource.
5. **Parallelism** — time-overlapping ops with DISJOINT footprints run concurrently (only
overlapping footprints are rejected).
Plus the PLACEMENT state-evolution: folding each op's effect over the schedule, with the
surface-code invariant that a static (surgery-only) schedule never moves a physical qubit.
Honesty: the full RSA-scale schedule (~10⁹ ops) is not constructed concretely; this engine + the
generic validity theorems here, plus the concrete schedules and bounds built on it
(`Bounds/NaiveSchedule`, `Bounds/ScheduleLowerBound`, `Bounds/ScheduleAdvance`), constitute the
verified system at the achievable level.
Self-contained beyond `RoutingResourceModel` (Nat/List only).
inductiveOpKind
inductive OpKind
The kind of a scheduled device operation.
structureDeviceOp
structure DeviceOp
A scheduled operation: its footprint of reserved resources during `[begin_t, begin_t+dur_t)`,
and the ids of operations that must COMPLETE before it may begin (`deps` — the wait edges:
magic readiness, decoder reaction, measurement feed-forward).
defDeviceOp.end_t
def DeviceOp.end_t (op : DeviceOp) : Nat
abbrevDSchedule
abbrev DSchedule
structureDevice
structure Device
Device configuration: total physical resources, decoder count, reaction-time bound, code-cycle
time, code distance.
defDeviceOp.isDecode
def DeviceOp.isDecode (op : DeviceOp) : Bool
defDeviceOp.activeAt
def DeviceOp.activeAt (op : DeviceOp) (t : Nat) : Bool
defopsTimeOverlap
def opsTimeOverlap (a b : DeviceOp) : Bool
Two ops overlap in time.
defDeviceOp.conflictsWith
def DeviceOp.conflictsWith (a b : DeviceOp) : Bool
Two ops conflict iff they overlap in time AND share a footprint resource.
defconflictFree
def conflictFree : DSchedule → Bool | [] => true | op :: rest => rest.all (fun o => ! op.conflictsWith o) && conflictFree rest
*(4) Space-time conflict-freedom** (recursive pairwise form). No two distinct ops overlap in
time AND share a footprint resource. Parallelism is ALLOWED: time-overlapping ops with disjoint
footprints pass. Recursive shape (head vs. all of tail, then recurse) for clean induction.
deffindOp
def findOp (sched : DSchedule) (oid : Nat) : Option DeviceOp
defdepsRespected
def depsRespected (sched : DSchedule) : Bool
*(2)+(3) Dependencies respected (the WAIT law).** Every dependency op exists and COMPLETES
before the dependent op begins. This enforces: magic produced+routed before consumed; decode
finished before a feed-forward-dependent op; ancilla prepared before use.
*WARNING — first-match-by-id, uniqueness not checked.** `findOp` returns the FIRST op whose
`id` matches; nothing enforces that ids are unique. If a schedule reuses an id, only the
first occurrence is consulted — a later duplicate that ends after the dependent begins is not
caught. Schedules are expected to carry unique ids; this checker does not verify that.
defboundaries
def boundaries (sched : DSchedule) : List Nat
Schedule boundary times (begin/end of every op, plus 0).
defactiveFootprintSize
def activeFootprintSize (sched : DSchedule) (t : Nat) : Nat
Total footprint resources reserved by ops active at time `t` (an upper bound on distinct
occupancy; exact when the schedule is conflict-free, since active footprints are then disjoint).
theoremactiveFootprintSize_cons
theorem activeFootprintSize_cons (o : DeviceOp) (rest : DSchedule) (t : Nat) :
activeFootprintSize (o :: rest) t
= (if o.activeAt t then o.footprint.length else 0) + activeFootprintSize rest tActive footprint of `o :: rest`: `o`'s footprint if active, plus the rest.
defcapacityRespected
def capacityRespected (dev : Device) (sched : DSchedule) : Bool
*(capacity)** At every boundary, the reserved footprint fits the device.
defdecoderQueueRespected
def decoderQueueRespected (dev : Device) (sched : DSchedule) : Bool
*(3) Decoder queue.** At every boundary, the number of active `decode` ops ≤ `nDecoders`.
defreactionRespected
def reactionRespected (dev : Device) (sched : DSchedule) : Bool
*(3) Reaction bound.** Every `decode` op completes within the reaction time.
defscheduleValid
def scheduleValid (dev : Device) (sched : DSchedule) : Bool
*★ END-TO-END device-schedule validity ★** — all five concerns at once.
theoremscheduleValid_components
theorem scheduleValid_components (dev : Device) (sched : DSchedule)
(h : scheduleValid dev sched = true) :
conflictFree sched = true ∧ depsRespected sched = true ∧ capacityRespected dev sched = true
∧ decoderQueueRespected dev sched = true ∧ reactionRespected dev sched = trueValidity projects to each component (so a valid schedule satisfies conflict-freedom, the wait
law, capacity, the decoder queue, and the reaction bound individually).
defDeviceOp.placementEffect
def DeviceOp.placementEffect (op : DeviceOp) (p : Placement) : Placement
An op's persistent effect on physical placement: a `move` applies its `RoutingKind`'s effect;
every other op leaves placement unchanged.
defevolvePlacement
def evolvePlacement (sched : DSchedule) (p0 : Placement) : Placement
Replay the schedule, evolving the physical placement op by op.
theoremevolvePlacement_cons
theorem evolvePlacement_cons (op : DeviceOp) (rest : DSchedule) (p0 : Placement) :
evolvePlacement (op :: rest) p0 = evolvePlacement rest (op.placementEffect p0)Replaying `op :: rest` = apply `op`'s effect, then replay `rest`.
defDeviceOp.isStatic
def DeviceOp.isStatic (op : DeviceOp) : Bool
An op is STATIC (moves no physical qubit) iff it is not a `transport` move.
theoremplacementEffect_static
theorem placementEffect_static (op : DeviceOp) (p : Placement) (h : op.isStatic = true) :
op.placementEffect p = pA static op leaves physical placement unchanged.
theoremevolvePlacement_static
theorem evolvePlacement_static : ∀ (sched : DSchedule) (p0 : Placement),
sched.all DeviceOp.isStatic = true → evolvePlacement sched p0 = p0
| [], _, _ => rfl
| op :: rest, p0, h =>*★ Surface-code placement invariant ★** — a STATIC schedule (no `transport` moves: pure
surface-code lattice surgery) never moves a physical qubit: the placement after replaying the
whole schedule equals the initial placement. (Contrast a transport/neutral-atom schedule,
which relocates qubits.)
FormalRV.System.DeviceLane.RoutingResourceModel
FormalRV/System/DeviceLane/RoutingResourceModel.lean
FormalRV.System.RoutingResourceModel — an ARCHITECTURE-AGNOSTIC model of routing & scheduling
as physical-resource RESERVATION, and proofs that it is consistent with concrete architectures
(surface-code lattice surgery à la Litinski 1808.02892, and movement-based neutral-atom/ion).
## The general concept (learned from, but not specific to, Litinski)
We deliberately do NOT introduce `Tile`, patch geometry, or any surface-code-specific type.
Instead we extract the GENERAL lesson that every fault-tolerant architecture shares:
A logical operation RESERVES a footprint of physical RESOURCES — its `operands` plus a
`routing` region used to connect/mediate them — for a time window.
ROUTING IS A RESERVATION, not a free side-effect: the routing region occupies real
resources for the operation's duration.
Two operations CONFLICT iff they overlap in time AND their reserved footprints share a
resource. (Surface code: ancilla-tile PATHS overlap. Neutral atom: transit CORRIDORS
overlap. Same rule.)
`routingQubits` is a general cost primitive — the SIZE of the reserved routing list, the
same list the exclusivity check reads (with a duplicates caveat; see §3).
## Consistency with the architectures (the point of this file)
The general `conflict`/`scheduleValid` is shown to be CONSISTENT with:
Litinski surface-code lattice surgery: instantiating `routing :=` the ancilla path, the
general conflict IS "two PPMs conflict iff their ancilla paths overlap"
(`litinski_simultaneous_conflict`). No tile type needed — resources are abstract ids and
the ancilla path is just the list of resources the surgery occupies.
Neutral-atom / trapped-ion movement: instantiating `routing :=` a transit corridor, the
general conflict is corridor exclusivity (`transit_conflict_is_corridor_overlap`).
The OLD operand-only exclusivity (`exclusivity_ok` on named operands): the degenerate case
`routing = []` (`conflict_no_routing`) — so the general model strictly REFINES it.
Self-contained (Nat/List only).
abbrevResource
abbrev Resource
An abstract physical resource unit: a qubit, a site, a tile-qubit — the granularity is the
architecture's choice; the laws below are agnostic to it.
structureResOp
structure ResOp
A scheduled operation reserves a footprint of resources — `operands` (the data resources it
acts on) plus `routing` (the region reserved to connect/mediate them) — during the window
`[begin_t, begin_t + dur_t)`.
defResOp.footprint
def ResOp.footprint (op : ResOp) : List Resource
The full reserved footprint: operands together with the routing region.
defResOp.routingQubits
def ResOp.routingQubits (op : ResOp) : Nat
*`routingQubits`** — the general routing cost = the length of the routing list (duplicates
counted; see the limitation noted at `routingQubits_is_reserved`).
deftimeOverlap
def timeOverlap (a b : ResOp) : Bool
Two operations overlap in time iff their windows intersect.
defoverlap
def overlap (s t : List Resource) : Bool
Two resource lists share a unit.
defconflict
def conflict (a b : ResOp) : Bool
*General conflict.** Two operations conflict iff they overlap in time AND their reserved
footprints (operands + routing) share a resource. This one rule subsumes surface-code
ancilla-path overlap and neutral-atom corridor overlap.
defscheduleValid
def scheduleValid (ops : List ResOp) : Bool
A schedule is VALID iff no two distinct operations conflict (footprint-exclusivity).
theoremno_conflict_if_disjoint_time
theorem no_conflict_if_disjoint_time (a b : ResOp) (h : timeOverlap a b = false) :
conflict a b = falseDisjoint-in-time operations never conflict — you can always serialize (wait).
theoremno_conflict_if_disjoint_footprint
theorem no_conflict_if_disjoint_footprint (a b : ResOp)
(h : overlap a.footprint b.footprint = false) : conflict a b = falseFootprint-disjoint operations never conflict — they run in parallel in different regions.
theoremroutingQubits_is_reserved
theorem routingQubits_is_reserved (op : ResOp) :
op.footprint.length = op.operands.length + op.routingQubitsLength accounting: `footprint.length = operands.length + routingQubits` (this is just
`List.length_append`). LIMITATION: footprints are LISTS with duplicates allowed, so an op can
inflate `routingQubits` (e.g. one resource id repeated 100 times reports cost 100) while the
exclusivity check (`overlap`) sees only that single resource. The count is tied to the
reserved list, not to the number of DISTINCT resources reserved.
theoremconflict_no_routing
theorem conflict_no_routing (a b : ResOp) (ha : a.routing = []) (hb : b.routing = []) :
conflict a b = (timeOverlap a b && overlap a.operands b.operands)With no routing reservation (`routing = []`), conflict reduces to OPERAND overlap — exactly the
old `exclusivity_ok`/`syscall_acts_on` behaviour (which named only operands). So the general
model agrees with the old one when routing is empty and catches MORE conflicts when routing is
present. This is the precise sense in which the general model REFINES the existing one.
deflatticeSurgeryOp
def latticeSurgeryOp (patch ancillaPath : List Resource) (clk : Nat) : ResOp
A surface-code lattice-surgery Pauli-product measurement, AS AN INSTANCE of the general model:
`operands` = the operand patch resources, `routing` = the ANCILLA-PATH resources it occupies
for 1 clock. No surface-code-specific type — resources are abstract ids; the ancilla path is
just the list of resources the surgery reserves.
theoremlitinski_simultaneous_conflict
theorem litinski_simultaneous_conflict (patch1 path1 patch2 path2 : List Resource) (clk : Nat) :
conflict (latticeSurgeryOp patch1 path1 clk) (latticeSurgeryOp patch2 path2 clk)
= overlap (patch1 ++ path1) (patch2 ++ path2)*★ Consistency with the paper ★.** For two simultaneous lattice-surgery PPMs, the general
`conflict` is EXACTLY "their footprints (operand patches + ancilla paths) overlap" — i.e.
Litinski's rule that two PPMs conflict iff their ancilla paths overlap (parallelproducts.tex
§parallel products). The general model thus faithfully captures surface-code surgery
scheduling, with NO tile/patch type.
theoremlitinski_routingQubits
theorem litinski_routingQubits (patch ancillaPath : List Resource) (clk : Nat) :
(latticeSurgeryOp patch ancillaPath clk).routingQubits = ancillaPath.lengthBy construction (`rfl`): `latticeSurgeryOp` stores `ancillaPath` in the `routing` field, so
its `routingQubits` is the ancilla-path length. Definitional glue, not a derived fact.
deftransitOp
def transitOp (src dst : Resource) (corridor : List Resource) (begin_t dur_t : Nat) : ResOp
A qubit transit, AS AN INSTANCE of the general model: `operands` = source & destination
resources, `routing` = the transit-corridor resources it occupies while moving.
theoremtransit_conflict_is_corridor_overlap
theorem transit_conflict_is_corridor_overlap
(s1 d1 s2 d2 : Resource) (c1 c2 : List Resource) (b dur : Nat) :
conflict (transitOp s1 d1 c1 b dur) (transitOp s2 d2 c2 b dur)
= (decide (0 < dur) && overlap ([s1, d1] ++ c1) ([s2, d2] ++ c2))For movement-based routing, the general conflict captures corridor/endpoint exclusivity: two
transits conflict iff (overlapping in time and) their corridors or endpoints share a resource.
The same general rule serves shuttling architectures.
defgA
def gA : ResOp
Operation `gA` acts on operands `{0,2}` and routes through resource `1`.
defgC
def gC : ResOp
Operation `gC` acts on DISJOINT operands `{10,12}` but routes through the SAME resource `1`.
theoremdisjoint_routing_parallel_ok
theorem disjoint_routing_parallel_ok :
scheduleValid [gA, { gC with routingAnd disjoint-routing operations run in parallel.
defreadyAt
def readyAt (inputEnds : List Nat) (t : Nat) : Bool
An operation is READY to start at `t` iff all its input-producing operations have completed by
`t` (their end times `≤ t`). This is the general produce-before-consume dependency — magic
states, ancilla preparation, prior measurement outcomes alike.
theoremmust_wait_for_inputs
theorem must_wait_for_inputs (inputEnds : List Nat) (t e : Nat) (he : e ∈ inputEnds) (hlt : t < e) :
readyAt inputEnds t = false*Wait law.** If any input completes after `t`, the operation is not ready at `t` — it must
wait. Architecture-agnostic (subsumes the magic-state readiness law).
abbrevPlacement
abbrev Placement
Which logical qubit (if any) physically occupies each resource (hardware slot); `none` = free.
defPlacement.set
def Placement.set (p : Placement) (r : Resource) (v : Option Nat) : Placement
Point update of a placement.
inductiveRoutingKind
inductive RoutingKind
The two routing paradigms, distinguished by their PERSISTENT effect on physical placement.
`transport q src dst` = a MOBILE architecture (neutral atom / ion) physically relocates the
qubit holding logical `q` from hardware slot `src` to `dst`. `surgery` = a STATIC architecture
(superconducting / surface-code lattice surgery): the operation is measurement-mediated through
transient ancilla and NO physical qubit moves.
defRoutingKind.applyPlacement
def RoutingKind.applyPlacement : RoutingKind → Placement → Placement | .transport q src dst, p => (p.set src none).set dst (some q) | .surgery, p => p
The persistent placement effect. Transport frees the source slot and occupies the destination;
surgery leaves the physical placement unchanged.
structureRoutedOp
structure RoutedOp
A routed operation pairs a transient RESERVATION (→ latency/conflict/throughput, SHARED across
architectures) with a routing KIND (→ persistent placement, DIFFERENT across architectures).
defroutedConflict
def routedConflict (a b : RoutedOp) : Bool
Conflict between routed ops is computed from their RESERVATIONS alone.
theoremroutedConflict_ignores_kind
theorem routedConflict_ignores_kind (a b : RoutedOp) (k : RoutingKind) :
routedConflict { a with kind*Conflict is kind-blind — by construction (`rfl`).** `routedConflict` reads only the
reservations, so changing the routing kind (transport ↔ surgery) cannot change it. This
records the DESIGN DECISION that scheduling treats neutral-atom and surface-code routing
identically; it is definitional, not a derived fact.
theoremsurgery_preserves_placement
theorem surgery_preserves_placement (p : Placement) :
RoutingKind.surgery.applyPlacement p = p*★ Surgery preserves physical placement ★** — surface-code lattice surgery moves no physical
qubit (the logical operation is measurement-mediated; the transient ancilla is freed). This is
the formal mark of a STATIC (superconducting) architecture.
theoremtransport_relocates
theorem transport_relocates (q src dst : Resource) (p : Placement) (h : dst ≠ src) :
(RoutingKind.transport q src dst).applyPlacement p dst = some q
∧ (RoutingKind.transport q src dst).applyPlacement p src = none*★ Transport relocates a physical qubit ★** — a neutral atom / ion physically travels, so the
operand's hardware slot CHANGES (source freed, destination occupied).
theoremtransport_changes_but_surgery_preserves
theorem transport_changes_but_surgery_preserves
(q src dst : Resource) (p : Placement) (h : dst ≠ src) (hq : p src = some q) (hfree : p dst = none) :
(RoutingKind.transport q src dst).applyPlacement p ≠ p
∧ RoutingKind.surgery.applyPlacement p = p*★ The crisp distinction ★.** When the source held `q` and the destination was free
(`src ≠ dst`), a TRANSPORT genuinely CHANGES the physical placement, whereas SURGERY leaves it
fixed. So the two architecture classes — identical in conflict / latency / throughput — differ
exactly in their physical mobility: neutral atoms move, surface-code qubits do not.
FormalRV.System.Examples.AdderSystem
FormalRV/System/Examples/AdderSystem.lean
FormalRV.System.Examples.AdderSystem — a concrete system-level
review instance: an adder-shaped SysCall schedule certified by
the strict invariant bundle, plus the gap-reporting pattern.
Full FT Shor at RSA-2048 scale cannot be built as a literal
`List SysCall` and decided with `native_decide`; an adder
skeleton is large enough to be structurally interesting (many
Gate2q / Measure / Decode / PauliFrameUpdate calls) yet small
enough that the entire strict checker bundle closes by
`native_decide`.
Contents: the 48-SysCall construction (§1–§2), the strict
system certificate (§3), resources derived by `foldl`/`filter`
over the actual schedule (§4), an optimistic paper-style claim
formally below the verified wallclock and below the Gate2q
capacity-bound formula (§5–§7), and a rejected over-parallel
variant (§8).
## What this is NOT
NOT an arithmetic-correctness review. The SysCall stream
is a system-level skeleton; it is NOT proven to implement
classical addition (see §9).
NOT a claim about specific paper numbers (Gidney–Ekerå,
Cain–Xu, etc.). The "optimistic claim" here is a generic
schema demonstrating the gap-reporting pattern.
NOT a final lower bound for adder construction. A
tighter compiler / more parallel hardware would produce a
smaller schedule. The bound is conditional on the chosen
`OperationCapacityModel`.
No Mathlib. No `sorry`. No custom `axiom`. All theorems
close by `native_decide`.
defadder_n1_syscalls
def adder_n1_syscalls : List SysCall
*The adder-skeleton SysCall schedule.** Sequential
composition of three PPM blocks, each with 3
syndrome-extraction rounds + 1 PauliFrameUpdate.
Size: `5·3 + 1 = 16` SysCalls per block × 3 blocks = 48
SysCalls. Wallclock: 16 µs per block × 3 blocks = 48 µs.
defadder_demo_arch
def adder_demo_arch : ZonedArch
Adder demo architecture: reuses `surgery_arch` (4 zones ×
100 sites).
defadder_demo_opCap
def adder_demo_opCap : OperationCapacityModel
Realistic operation-capacity model: tight Gate2q + finite
measure/decode/feedback parallelism.
defadder_demo_slotCap
def adder_demo_slotCap : SlotCapacityModel
Slot capacity model: 4 zones, each generously sized
relative to the adder skeleton's resource usage.
defadder_demo_ancillaModel
def adder_demo_ancillaModel : AncillaModel
Ancilla freshness model: one zone, id 1, sites
`[100, 200)`. Matches `surgery_ppm_A`'s
`RequestFreshAncilla 1` convention.
defadder_demo_t_react_us
def adder_demo_t_react_us : Nat
defadder_demo_window_us
def adder_demo_window_us : Nat
defadder_demo_max_per_window
def adder_demo_max_per_window : Nat
theoremadder_n1_strict_system_ok
theorem adder_n1_strict_system_ok :
all_invariants_strict_with_slot_capacity_and_freshness_ok
adder_demo_arch
adder_demo_opCap
adder_demo_slotCap
adder_demo_ancillaModel
adder_n1_syscalls
adder_demo_t_react_us
adder_demo_window_us
adder_demo_max_per_window = true*The headline system certificate.** The adder skeleton
passes the strongest current invariant bundle:
`all_invariants_with_factory_ports_ok` ∧
`operation_capacity_ok` ∧ `feedback_after_decode_ok` ∧
`slot_capacity_ok` ∧ `ancilla_freshness_ok`.
defadder_n1_wallclock_us
def adder_n1_wallclock_us : Nat
Wallclock, derived (not typed in): `scheduleWallclockUs` is
`foldl Nat.max sc.end_us 0` over the actual schedule.
defadder_n1_syscall_count
def adder_n1_syscall_count : Nat
Total SysCall count.
defadder_n1_gate2q_count
def adder_n1_gate2q_count : Nat
Total `Gate2q` count.
defadder_n1_measure_count
def adder_n1_measure_count : Nat
Total `Measure` count.
defadder_n1_decode_count
def adder_n1_decode_count : Nat
Total `DecodeSyndrome` count.
defadder_n1_feedback_count
def adder_n1_feedback_count : Nat
Total `PauliFrameUpdate` (feedback) count.
defadder_n1_fresh_ancilla_count
def adder_n1_fresh_ancilla_count : Nat
Total `RequestFreshAncilla` count.
theoremadder_n1_wallclock_value
theorem adder_n1_wallclock_value :
adder_n1_wallclock_us = 48Wallclock value: 48 µs. Three sequential PPM blocks at
16 µs each.
theoremadder_n1_syscall_count_value
theorem adder_n1_syscall_count_value :
adder_n1_syscall_count = 4848 SysCalls total.
theoremadder_n1_gate2q_count_value
theorem adder_n1_gate2q_count_value :
adder_n1_gate2q_count = 1818 Gate2qs: 6 per PPM × 3 PPMs.
theoremadder_n1_measure_count_value
theorem adder_n1_measure_count_value :
adder_n1_measure_count = 99 Measures: 3 per PPM × 3 PPMs.
theoremadder_n1_decode_count_value
theorem adder_n1_decode_count_value :
adder_n1_decode_count = 99 DecodeSyndromes: 3 per PPM × 3 PPMs.
theoremadder_n1_feedback_count_value
theorem adder_n1_feedback_count_value :
adder_n1_feedback_count = 33 PauliFrameUpdates: 1 per PPM × 3 PPMs.
theoremadder_n1_fresh_ancilla_count_value
theorem adder_n1_fresh_ancilla_count_value :
adder_n1_fresh_ancilla_count = 99 RequestFreshAncillas: 3 per PPM × 3 PPMs.
structureAdderSystemClaim
structure AdderSystemClaim
defoptimistic_parallel_adder_claim
def optimistic_parallel_adder_claim : AdderSystemClaim
A deliberately optimistic claim object: "the adder
completes in 1 µs with 1 Gate2q, 1 Measure, 1 decode".
Used to demonstrate the gap-reporting pattern. No paper
is being accused of this exact number — it is a SCHEMA.
theoremoptimistic_adder_claim_underestimates_verified_schedule
theorem optimistic_adder_claim_underestimates_verified_schedule :
optimistic_parallel_adder_claim.claimed_wallclock_us
< adder_n1_wallclock_us*Direct gap (smallest form)**: the optimistic claim's
wallclock is strictly below the verified construction's
wallclock.
Interpretation: this does NOT prove the optimistic claim
is impossible for ALL adder constructions; it proves the
claim is FALSE for the concrete certified construction
above.
theoremoptimistic_adder_claim_understates_verified_gate2qs
theorem optimistic_adder_claim_understates_verified_gate2qs :
optimistic_parallel_adder_claim.claimed_gate2q_count
< adder_n1_gate2q_countGate2q-count gap.
defgate2q_capacity_lower_bound_us
def gate2q_capacity_lower_bound_us
(num_gate2q max_parallel gate2q_us : Nat) : NatThe Gate2q capacity lower bound: with `max_parallel`
parallel Gate2qs each taking `gate2q_us` µs, serving
`num_gate2q` Gate2qs total takes at least
`ceildiv(num_gate2q, max_parallel) · gate2q_us` µs.
theoremadder_n1_gate2q_capacity_lower_bound_value
theorem adder_n1_gate2q_capacity_lower_bound_value :
gate2q_capacity_lower_bound_us
adder_n1_gate2q_count
adder_demo_opCap.max_gate2q_active
1 = 18Numerical lower bound for this review: 18 Gate2qs / 1
parallel / 1 µs each = 18 µs.
theoremoptimistic_adder_claim_below_gate2q_capacity_lower_bound
theorem optimistic_adder_claim_below_gate2q_capacity_lower_bound :
optimistic_parallel_adder_claim.claimed_wallclock_us
< gate2q_capacity_lower_bound_us
adder_n1_gate2q_count
adder_demo_opCap.max_gate2q_active
1*Capacity lower-bound gap**: the optimistic claim's 1 µs is
formally below the 18 µs capacity floor computed under the
same `OperationCapacityModel` used to certify the schedule.
Informal reading: 18 Gate2qs served one at a time take 18 µs,
so the claim contradicts its own capacity assumptions. (The
formal content is the numeral comparison; the universally
quantified bound is not formalised — see the §7 header.)
defbad_parallel_adder_syscalls
def bad_parallel_adder_syscalls : List SysCall
A bad adder-skeleton schedule: two PPM blocks in
parallel. Rejected by operation capacity.
theorembad_parallel_adder_schedule_rejected
theorem bad_parallel_adder_schedule_rejected :
all_invariants_strict_with_slot_capacity_and_freshness_ok
adder_demo_arch
adder_demo_opCap
adder_demo_slotCap
adder_demo_ancillaModel
bad_parallel_adder_syscalls
adder_demo_t_react_us
adder_demo_window_us
adder_demo_max_per_window = false*Bad-schedule rejection theorem.** Direct "lack of
system consideration causes failure" example.
example(example)
example : adder_n1_syscalls.length = 3 * 16
A purely structural cross-reference: the certified
construction has 3 PPM blocks, which structurally
correspond to the 3 stabilizer-extraction rounds that a
single Cuccaro-style MAJ/UNMAJ gadget would consume. No
semantic claim.
FormalRV.System.Examples.ConcreteMachineFeasibility
FormalRV/System/Examples/ConcreteMachineFeasibility.lean
FormalRV.System.Examples.ConcreteMachineFeasibility — two independent
demonstrations that a resource estimate is only meaningful relative to a
concrete machine:
(1) SPACE FEASIBILITY (§1–§2): whether a fixed physical-qubit budget can
hold the RSA-2048 data block — 6200 logical patches × `2(d+1)²`
physical qubits each, all live simultaneously (they hold the quantum
state, so they cannot be time-shared). A 100 000-qubit machine
cannot, at any useful distance; a 20 M machine can at d = 27.
(2) CONNECTIVITY (§3): a pluggable coupling-map `SpaceTimeInvariant` —
nearest-neighbour rejects a long-range Gate2q that all-to-all admits
(superconducting / trapped-ion / neutral-atom each supply their own
`couples`).
The two halves are unrelated beyond sharing the SysCall / invariant
vocabulary. No `sorry`, no new `axiom`.
defsurfaceTile
def surfaceTile (d : Nat) : Nat
A distance-`d` rotated surface tile: `2(d+1)²` physical qubits per logical.
defrsa2048_logical
def rsa2048_logical : Nat
RSA-2048's live logical-qubit count: the canonical `RSA2048.patches`
(= 6200, Ekerå–Håstad windowed layout).
defrsa2048_dataPhysical
def rsa2048_dataPhysical (d : Nat) : Nat
Physical qubits the RSA-2048 DATA BLOCK needs at distance `d` (all live at
once — not time-shareable).
defmachineFitsRSA2048
def machineFitsRSA2048 (budget d : Nat) : Bool
A concrete machine FITS the RSA-2048 data block at distance `d` iff its qubit
budget covers it.
theoremrsa2048_dataPhysical_d27
theorem rsa2048_dataPhysical_d27 : rsa2048_dataPhysical 27 = 9_721_600
The data block at d=27 is 6200 · 1568 = 9,721,600 physical qubits.
defmachine100k
def machine100k : Nat
theoremmachine100k_cannot_factor_rsa2048_d27
theorem machine100k_cannot_factor_rsa2048_d27 :
machineFitsRSA2048 machine100k 27 = false*INFEASIBLE.** A 100 000-qubit machine cannot hold the RSA-2048 data block
at d=27 (needs 9.72 M ≫ 100 k).
theoremrsa2048_space_lower_bound
theorem rsa2048_space_lower_bound (budget : Nat)
(h : machineFitsRSA2048 budget 27 = true) : 9_721_600 ≤ budgetThe space requirement is a genuine lower bound: ANY machine that fits RSA-2048
at d=27 has at least 9,721,600 qubits.
theoremmachine100k_infeasible_even_d3
theorem machine100k_infeasible_even_d3 :
machineFitsRSA2048 machine100k 3 = falseEven at the SMALLEST error-correcting distance d=3 (tile 32), RSA-2048's data
block is 6200·32 = 198,400 > 100 k — still infeasible. 100 k cannot factor
RSA-2048 at ANY useful distance.
theoremmachine100k_holds_63_logical_d27
theorem machine100k_holds_63_logical_d27 :
machine100k / surfaceTile 27 = 63What a 100 k machine CAN hold at d=27: ⌊100000 / 1568⌋ = 63 logical qubits —
enough only for a tiny (~20-bit) factoring instance, not RSA-2048's 6200.
theoremmachine20M_fits_rsa2048_d27
theorem machine20M_fits_rsa2048_d27 :
machineFitsRSA2048 20_000_000 27 = trueA machine that DOES fit RSA-2048 at d=27 (e.g. Gidney's 20 M).
defconnectivityInv
def connectivityInv (couples : Nat → Nat → Bool) : SpaceTimeInvariant
A hardware connectivity constraint: every 2-qubit gate must act on a pair the
machine can DIRECTLY couple, per `couples`. Long-range gates must be routed
(SWAP) and fail this until decomposed. Hardware-specific: superconducting
nearest-neighbour, trapped-ion all-to-all (`fun _ _ => true`), neutral-atom
reconfigurable each supply their own `couples`.
defnearestNeighbor1D
def nearestNeighbor1D (q1 q2 : Nat) : Bool
1-D nearest-neighbour coupling (the canonical superconducting constraint).
defnnSched
def nnSched : List SysCall
A small schedule whose 2-qubit gates are all nearest-neighbour.
defnnCtx
def nnCtx : SystemCtx
theoremnnCtx_connectivity_ok
theorem nnCtx_connectivity_ok :
(connectivityInv nearestNeighbor1D).check nnCtx = true*Respects nearest-neighbour connectivity.**
deflongRangeSched
def longRangeSched : List SysCall
A schedule with a LONG-RANGE gate (qubits 0 and 5, distance 5) on a
nearest-neighbour machine.
deflongRangeCtx
def longRangeCtx : SystemCtx
theoremlongRange_rejected
theorem longRange_rejected :
(connectivityInv nearestNeighbor1D).check longRangeCtx = false*REJECTED**: a long-range gate violates nearest-neighbour connectivity — it
must be routed by SWAPs first. Connection constraints are real, not advisory.
theoremnnCtx_fully_valid
theorem nnCtx_fully_valid :
checkAll (baseInvariants ++ [connectivityInv nearestNeighbor1D]) nnCtx = trueThe nearest-neighbour schedule passes the FULL check (resource A + connectivity
as a composed hardware invariant) — one uniform `checkAll`.
theoremlongRange_ok_on_all_to_all
theorem longRange_ok_on_all_to_all :
(connectivityInv (fun _ _ => true)).check longRangeCtx = trueTrapped-ion all-to-all coupling (`couples = fun _ _ => true`) admits the
long-range gate the nearest-neighbour machine rejected — the SAME schedule,
different hardware connectivity.
FormalRV.System.Examples.CostModelWeightDemo
FormalRV/System/Examples/CostModelWeightDemo.lean
FormalRV.System.Examples.CostModelWeightDemo — wiring the purpose-tagged
ancilla budget to REAL code data (headline:
`surgery_ancilla_is_verified_logical_weight`).
The qLDPC `CostModel` (`Framework/CostModel.lean`) tags ancilla by purpose.
This file shows the two operator-dependent tags are computed from genuine repo
objects, NOT magic constants:
• SYNDROME ancilla = the code's actual parity-check count `|hx| + |hz|`
(read from `code422`'s real check matrices).
• SURGERY ancilla = the measured logical operator's PHYSICAL WEIGHT,
`rowWeight (L.selectZ S)` — the Hamming weight of the VERIFIED logical
operator from `QEC/Logical.lean` + `QEC/Addressing.lean`
(`code422Logical`, whose `valid = true`).
Worked on the [[4,2,2]] code and its verified logical basis. This closes the
loop: the resource cost a verifier reads off is sourced from the same logical
operators it already proved correct.
No Mathlib. `decide` only.
defcode422Q
def code422Q : FormalRV.Framework.QECCode
The [[4,2,2]] code as a flat `QECCode` (k = 2, d = 2), carrying its real
parity-check matrices `hx = [XXXX]`, `hz = [ZZZZ]`.
defw0
def w0 : Workload
Dummy workload (the operator-dependent ancilla tags ignore it).
example(example)
example : rowWeight (code422Logical.selectZ [0]) = 2
The PHYSICAL WEIGHT of the logical operator Z̄₀ = Z₀Z₂ on [[4,2,2]], read off
the verified logical basis: `rowWeight (selectZ [0]) = 2`.
theoremsurgery_ancilla_is_verified_logical_weight
theorem surgery_ancilla_is_verified_logical_weight :
((qldpcModel 0).ancilla code422Q w0 (rowWeight (code422Logical.selectZ [0])) 1).surgery = 2*The main wiring claim.** The qLDPC SURGERY ancilla for measuring Z̄₀
equals the operator's real weight (2), fed in as
`op_weight = rowWeight (selectZ [0])` — read off the verified logical
basis, not a magic constant.
example(example)
example : rowWeight (code422Logical.selectZ [0, 1]) = 2
The weight-2 product Z̄₀Z̄₁ = `selectZ [0,1]` (= Z₁Z₂) is also weight 2 ⇒
surgery ancilla 2. A heavier product scales the surgery tag up linearly.
example(example)
example : ((qldpcModel 0).ancilla code422Q w0 7 1).syndrome = 1
Wiring: the qLDPC SYNDROME ancilla = qianxu's one-basis stabilizer count
`(n-k)/2 = (4-2)/2 = 1` (the `op_weight` argument is irrelevant here).
example(example)
example : ((qldpcModel 0).ancilla code422Q w0 (rowWeight (code422Logical.selectZ [0])) 1).syndrome = 1
For measuring Z̄₀ on [[4,2,2]] under the qLDPC model:
syndrome 1 ((n-k)/2, qianxu) + surgery 2 (real weight) ⇒ total 3 (the flat
count the purpose-agnostic `RequestFreshAncilla` syscall provisions).
example(example)
example : ((qldpcModel 0).ancilla code422Q w0 (rowWeight (code422Logical.selectZ [0])) 1).surgery = 2
example(example)
example : ((qldpcModel 0).ancilla code422Q w0 (rowWeight (code422Logical.selectZ [0])) 1).total = 3
FormalRV.System.Examples.ParallelismVerification
FormalRV/System/Examples/ParallelismVerification.lean
FormalRV.System.Examples.ParallelismVerification — the system-level
framework expresses parallelism and its limits.
Parallelism in the Cain–Xu setting (App. B/E/F) splits into exactly TWO
classes, and the framework expresses both:
(A) RESOURCE-CAPACITY constraints — `demand ≤ capacity`. What CAN'T overlap:
two ops can run concurrently only if they don't exceed a shared resource.
Captured by the extensible `checkAll` invariants, every one of which is
ACTIVE-SET / OVERLAP based (genuinely concurrency-aware, not a sequential
approximation):
• exclusivity — time-overlapping ops claim DISJOINT atoms;
• capacity/cycle — the active set's per-zone load ≤ zone capacity;
• throughput — factory production rate over any window;
• decoder reaction — each decode finishes within the reaction budget;
• + extensible: rigid AOD parallel moves, decoder CONCURRENCY (§D).
(B) CAUSAL DEPENDENCIES — a partial order on operations. What MUST be
sequential: producer must finish before consumer starts. Captured by
`Architecture.semantically_correct` (measure → decode → feed-forward;
teleport-in → compute → teleport-out; no double-measure).
"Maximum parallelism subject to system invariants" is then PRECISELY: two
operations may run concurrently iff they have no resource conflict (A) AND no
causal dependency (B). This is the standard dependency-DAG + resource-
constraint model of correct parallel scheduling, and the framework decides it.
§C certifies ONLY the disjointness precondition of the sequentializability
argument (time-overlapping ops act on disjoint atoms, hence share no qubit);
the commutation step and a "parallel ≡ sequential" theorem are NOT
formalised here or elsewhere in the SysCall layer.
EXTENSIBILITY: any future parallelism limit is ONE more `SpaceTimeInvariant`
that ANDs in via `checkAll_snoc` without touching the others
(`checkAll_mono`). §D adds decoder-concurrency as a worked example.
Residues (honest): the syscall layer is non-semantic by design (per-op
semantics live at the PPM layer). Adaptive/feed-forward branching is
abstracted via reaction-time bounds, not modelled as data-dependent
control flow.
No Mathlib. Pure Bool / Nat + `decide`. No `sorry`, no `axiom`.
defparallelSched
def parallelSched : List SysCall
defparallelCtx
def parallelCtx : SystemCtx
example(example)
example : ∀ s ∈ parallelSched, s.begin_us = 0 ∧ s.end_us = 10
These five operations genuinely run CONCURRENTLY — every one occupies the
same window [0,10). This is not a sequential schedule.
example(example)
example : checkAll baseInvariants parallelCtx = true
MAX PARALLELISM IS VALID: the fully-concurrent four-zone schedule passes
EVERY base invariant. This is "maximum parallelism allowed as long as the
system invariants hold", machine-checked.
defconflictCtx
def conflictCtx : SystemCtx
ATOM CONFLICT: two concurrent measurements on the SAME atom 5. Exclusivity
rejects — you cannot run two ops on one qubit at once.
example(example)
example : checkAll baseInvariants conflictCtx = false
defthroughputViolCtx
def throughputViolCtx : SystemCtx
THROUGHPUT: two magic-state requests inside one factory window, with
`max_per_window = 1`. Window-throughput rejects — the factory cannot supply
faster than its rate (qianxu: 12 cycles per |CCZ⟩).
example(example)
example : checkAll baseInvariants throughputViolCtx = false
defslowDecodeCtx
def slowDecodeCtx : SystemCtx
DECODER REACTION: a decode that runs longer than the reaction budget
(`t_react_us = 10`). The decoder invariant rejects — real-time decoding must
keep up with the cycle stream.
example(example)
example : checkAll baseInvariants slowDecodeCtx = false
defcausalSched
def causalSched : Schedule
A measure → decode → feed-forward chain respects the causal order: every
SysCall's precondition is met (decode sees a prior measurement; the frame
update sees a prior decode).
example(example)
example : semantically_correct [] neutral_atom_mini causalSched = true
defbadCausalSched
def badCausalSched : Schedule
VIOLATION: decoding BEFORE any measurement. The framework rejects it — the
measure → decode dependency cannot be parallelised away.
example(example)
example : semantically_correct [] neutral_atom_mini badCausalSched = false
example(example)
example : exclusivity_ok parallelSched = true
Every time-overlapping ordered pair in the parallel schedule acts on
disjoint atoms — the certified disjointness precondition.
defdecodeDepthAt
def decodeDepthAt (sched : List SysCall) (t : Nat) : Nat
Number of `DecodeSyndrome` calls active at time `t`.
defdecoderConcurrencyInv
def decoderConcurrencyInv (n_decoders : Nat) : SpaceTimeInvariant
NEW invariant: at every begin-time, at most `n_decoders` decoders run
concurrently (classical-compute parallelism limit — qianxu's decoder
ensemble).
example(example)
example (c : SystemCtx) (n : Nat) :
checkAll (baseInvariants ++ [decoderConcurrencyInv n]) c
= (checkAll baseInvariants c && (decoderConcurrencyInv n).check c)Adding it ANDs in its check WITHOUT affecting the base invariants
(`checkAll_snoc` instantiated) — the extensibility guarantee.
deftwoDecodeCtx
def twoDecodeCtx : SystemCtx
A context with TWO concurrent decodes; both run in [0,10).
example(example)
example : checkAll (baseInvariants ++ [decoderConcurrencyInv 2]) twoDecodeCtx = true
With a 2-decoder budget the extended set passes (2 concurrent ≤ 2).
example(example)
example : checkAll (baseInvariants ++ [decoderConcurrencyInv 1]) twoDecodeCtx = false
With only a 1-decoder budget, the NEW invariant rejects the 2-concurrent-
decode schedule…
example(example)
example : checkAll baseInvariants twoDecodeCtx = true
…while the BASE invariants still pass on it — adding the new constraint does
not interfere with the existing guarantees (non-interference).
FormalRV.System.Examples.SystemInvariantExamples
FormalRV/System/Examples/SystemInvariantExamples.lean
FormalRV.System.Examples.SystemInvariantExamples — five worked device programs checked against
the system-level invariants (I1 capacity, I2 exclusivity, I3 latency/speed + decoder-reaction,
I4 factory throughput), TWO that PASS and THREE that FAIL.
Every pass/fail verdict is a `native_decide` theorem, regression-checked by the umbrella
`lake build` (imported by `FormalRV/System.lean`). The matching emitted `DEVICE-PROGRAM` text
is printed by the standalone demo `FormalRV/Codegen/SysCallEmitDemo.lean`.
Workflow: build a `Schedule` (physical ops + system calls) → CHECK with
`ScheduleInv.all_invariants_ok` → emit. `ZonedArch` carries `t_react_us`, so the headline
`all_invariants_ok` enforces ALL of I3 (feedback + speed + decoder reaction).
defdemoArch
def demoArch : ZonedArch
A tiny architecture: a Data zone `[0,100)`, an Ancilla zone `[100,200)`, and a Factory zone
`[200,300)`; 1 µs stabilizer cycle, no transit (`v_max = 0`), 10 µs decoder reaction budget.
defwinUs
def winUs : Nat
Factory window: the CCZ factory makes ≤ 1 magic state per window (the canonical
`RSA2048.cczWindowUs` = 12 000 µs, Cain–Xu 2026 App. C).
defmaxPerWin
def maxPerWin : Nat
defnoDist
def noDist : Nat → Nat
defppm
def ppm (start data anc dec : Nat) : List SysCall
One PPM measurement (request ancilla → joint gate → measure → decode), parametric in start
time, data qubit, ancilla qubit, decoder id. The decode takes 1 µs (≤ the 10 µs budget).
defpassSequential
def passSequential : List SysCall
theorempassSequential_ok
theorem passSequential_ok : all_invariants_ok demoArch passSequential winUs maxPerWin noDist = true
defpassParallelDistinct
def passParallelDistinct : List SysCall
theorempassParallelDistinct_ok
theorem passParallelDistinct_ok :
all_invariants_ok demoArch passParallelDistinct winUs maxPerWin noDist = truetheorempassParallelDistinct_overlaps
theorem passParallelDistinct_overlaps : intervals_overlap 1 2 1 2 = true
Pins the interval arithmetic only: `[1,2)` overlaps itself. The statement does NOT
reference the schedule — both PPMs' joint gates occupy `[1,2)` by construction of
`passParallelDistinct` (`ppm start …` places the `Gate2q` in `[start+1, start+2)` and
both PPMs start at 0), so this is the overlap fact that construction instantiates.
deffailAlias
def failAlias : List SysCall
theoremfailAlias_fails
theorem failAlias_fails : all_invariants_ok demoArch failAlias winUs maxPerWin noDist = false
theoremfailAlias_exclusivity_false
theorem failAlias_exclusivity_false : exclusivity_ok failAlias = false
theoremfailAlias_capacity_true
theorem failAlias_capacity_true : capacity_in_arch_ok demoArch failAlias = true
deffailThroughput
def failThroughput : List SysCall
theoremfailThroughput_fails
theorem failThroughput_fails :
all_invariants_ok demoArch failThroughput winUs maxPerWin noDist = falsetheoremfailThroughput_window_false
theorem failThroughput_window_false : window_throughput_ok failThroughput winUs maxPerWin = false
theoremfailThroughput_others_true
theorem failThroughput_others_true :
(capacity_in_arch_ok demoArch failThroughput && exclusivity_ok failThroughput) = truedeffailDecodeSlow
def failDecodeSlow : List SysCall
theoremfailDecodeSlow_fails
theorem failDecodeSlow_fails :
all_invariants_ok demoArch failDecodeSlow winUs maxPerWin noDist = falseThe headline bundle REJECTS the too-slow decode (decoder reaction is enforced).
theoremfailDecodeSlow_decoder_react_false
theorem failDecodeSlow_decoder_react_false :
decoder_react_ok demoArch.t_react_us failDecodeSlow = falseThe specific failing component is I3 decoder-reaction; I1/I2/I4 still hold.
theoremfailDecodeSlow_others_true
theorem failDecodeSlow_others_true :
(capacity_in_arch_ok demoArch failDecodeSlow && exclusivity_ok failDecodeSlow
&& window_throughput_ok failDecodeSlow winUs maxPerWin) = trueFormalRV.System.FTFramework
FormalRV/System/FTFramework.lean
FormalRV.System.FTFramework — the single entry point for the fault-tolerant scheduling
framework, tying together the two subsystems that grew in parallel:
canonical hardware — `HardwareParams.MachineParams` (incl. the one decoder-reaction
budget, reconciled across the legacy records);
schedule well-formedness — `DeviceSchedule.scheduleValid` (conflict / wait / capacity /
decoder / reaction) and `ScheduleInv.all_invariants_ok`;
resource BRACKET — `ScheduleBounds.resource_bracket` (lower floor ≤ workload ≤
upper ceiling) + `naive_peak_le_total` (peak ≤ footprint);
hardware SENSITIVITY — `HardwareSensitivity.HW.timeLB` (max-of-four-floors bound,
monotone in every hardware parameter).
`FTSystem` bundles the hardware + device + schedule, and `ftSystem_naive_guarantee` certifies —
for ANY size, without enumeration — that a naive system on an adequate device is valid,
reaction-bounded, and footprint-bounded. The GE2021 instance is proven PARAMETRICALLY (never
instantiating the ~8×10⁹-op schedule concretely).
structureFTSystem
structure FTSystem
A fault-tolerant system under test: canonical hardware + the device view + the schedule.
abbrevtimeLowerBound
abbrev timeLowerBound : HardwareSensitivity.HW → Nat → Nat → Nat
Re-export: the hardware-sensitivity runtime lower bound (max of the four resource/causal
floors), the single front-door for "how the bound responds to each hardware parameter".
theoremftSystem_naive_guarantee
theorem ftSystem_naive_guarantee
(S : FTSystem) (M : Nat)
(hsched : S.sched = naiveSchedule M)
(hdev : adequate S.dev) :
scheduleValid S.dev S.sched = true
∧ reactionRespected S.dev S.sched = true
∧ schedulePeak S.sched ≤ S.dev.totalResources*★ The umbrella guarantee ★** — for ANY operation count `M`, a naive system on an adequate
device is simultaneously:
(i) a VALID schedule, (ii) decoder-reaction bounded, (iii) footprint (capacity) bounded —
proven parametrically (no enumeration), composing `naiveSchedule_valid`,
`reactionRespected_naive`, and `naive_peak_le_total`.
defgeSystem
def geSystem : FTSystem
GE2021 system: 20M-qubit / 10 µs-reaction / d=27 device running the full naive RSA-2048
schedule (`3 · 2 622 824 448` ops), hardware mirrored from the device.
theoremgeSystem_guarantee
theorem geSystem_guarantee :
scheduleValid geSystem.dev geSystem.sched = true
∧ reactionRespected geSystem.dev geSystem.sched = true
∧ schedulePeak geSystem.sched ≤ geSystem.dev.totalResourcesThe GE2021 system is valid, reaction-bounded and footprint-bounded — via the umbrella, for the
full ~8×10⁹-op schedule, without ever enumerating it.
FormalRV.System.Invariants.InvariantFramework
FormalRV/System/Invariants/InvariantFramework.lean
FormalRV.System.Invariants.InvariantFramework — EXTENSIBLE SPACE-TIME
INVARIANT FRAMEWORK (namespace `FormalRV.System.InvariantFramework`).
Part of the unified FT-scheduling framework — see `FormalRV.System.FTFramework` for the single
entry point. This is the `SysCall`-side extensible invariant checker; its `DeviceOp` sibling is
`FormalRV.System.DeviceSchedule.scheduleValid`. Connected at the umbrella, not merged.
The fixed resources are qubits/atoms (space), classical compute, and time; a
schedule makes claims on them. Every system invariant is a space-time
PROPOSITION over these resources — a `SpaceTimeInvariant` (named decidable
predicate on `SystemCtx`). They live in an OPEN list checked uniformly by
`checkAll`; `checkAll_snoc`/`checkAll_mono` prove that appending an invariant
ANDs in its check WITHOUT affecting the others, so a future FT-OS author
extends coverage by appending one instance — never editing existing
invariants. The standard scheduling rules (capacity = ancilla, exclusivity,
latency/speed = routing, throughput = T-factory, decoder) are instances
(`baseInvariants`); `neutralAtomRigidMoveInv` shows the framework captures
INSTRUCTION-LEVEL hardware limits too (neutral-atom rigid parallel movement —
time-overlapping atom moves must share a displacement).
FTSchedule.ft_ok is recoverable as `checkAll baseInvariants c &&
distance_adequate`.
No Mathlib. Pure List / Bool / Nat + `decide`. No `sorry`, no `axiom`,
no `admit`.
structureTransport
structure Transport
A qubit-TRANSPORT resource usage (hardware-neutral): qubit `id` moves from
`fromPos` to `toPos` over [begin_us, end_us). Positions are layout coords
(row, col). How transport is physically realised — neutral-atom AOD shuttle,
superconducting SWAP routing, ion-shuttle — is a HARDWARE-SPECIFIC invariant,
not part of this generic event.
structureSystemCtx
structure SystemCtx
The fixed resources + schedule a system invariant is a proposition about:
the zoned architecture (qubit/atom slots in space + timing params), the
syscall schedule (resource claims in space-time), the atom-move schedule,
and the throughput/decoder window parameters.
structureSpaceTimeInvariant
structure SpaceTimeInvariant
A space-time proposition over the fixed resources: a named decidable
predicate on the system context.
defcheckAll
def checkAll (invs : List SpaceTimeInvariant) (c : SystemCtx) : Bool
Mechanical uniform check: every invariant in the (open) list holds.
theoremcheckAll_append
theorem checkAll_append (a b : List SpaceTimeInvariant) (c : SystemCtx) :
checkAll (a ++ b) c = (checkAll a c && checkAll b c)theoremcheckAll_snoc
theorem checkAll_snoc (invs : List SpaceTimeInvariant) (inv : SpaceTimeInvariant)
(c : SystemCtx) :
checkAll (invs ++ [inv]) c = (checkAll invs c && inv.check c)theoremcheckAll_mono
theorem checkAll_mono (invs extra : List SpaceTimeInvariant) (c : SystemCtx)
(h : checkAll (invs ++ extra) c = true) : checkAll invs c = trueMonotonicity: extending the invariant set can only restrict — a schedule
valid under more invariants is valid under fewer. So adding invariants
never breaks an existing guarantee.
defcapacityInv
def capacityInv : SpaceTimeInvariant
defexclusivityInv
def exclusivityInv : SpaceTimeInvariant
deflatencyInv
def latencyInv : SpaceTimeInvariant
defthroughputInv
def throughputInv : SpaceTimeInvariant
defdecoderInv
def decoderInv : SpaceTimeInvariant
defbaseInvariants
def baseInvariants : List SpaceTimeInvariant
The standard scheduling rules as a base set. `checkAll baseInvariants c`
is the schedulability core of `FTSchedule.ft_ok` minus distance adequacy.
defmovesOverlap
def movesOverlap (a b : Transport) : Bool
Two moves overlap in time.
defsameDisplacement
def sameDisplacement (a b : Transport) : Bool
Equal displacement (Nat-safe via cross-addition, avoiding subtraction):
(to-from) of a equals (to-from) of b in both coordinates.
defneutralAtomRigidMoveInv
def neutralAtomRigidMoveInv : SpaceTimeInvariant
Neutral-atom parallel-move constraint: any two time-overlapping atom moves
must have the same displacement (rigid lattice translation — "same pace").
An INSTRUCTION-LEVEL hardware limit, expressed as a space-time invariant.
defsuperconductingFixedCouplingInv
def superconductingFixedCouplingInv : SpaceTimeInvariant
Superconducting fixed-coupling constraint: superconducting qubits have FIXED
nearest-neighbour coupling and do NOT physically move — routing is done by
SWAP gates, not by transporting qubits. So a superconducting schedule carries
NO `Transport` events. A superconducting-only instruction-level limit, the
sibling of `neutralAtomRigidMoveInv`; both compose onto the SAME hardware-
neutral `baseInvariants`. (Surface-code lattice surgery runs on both platforms.)
defdemoArch
def demoArch : ZonedArch
Worked-instance architecture (local copy of `FTSchedule.demoArch`).
defdemoDist
def demoDist : Nat → Nat
Route distance function: every channel covers 30 µm (local copy of
`FTSchedule.demoDist`).
defdemoSched
def demoSched : List SysCall
Worked-instance schedule (local copy of `FTSchedule.demoSched`).
defdemoMoves
def demoMoves : List Transport
Two COHERENT parallel atom moves: both displace by (0,+1) (one lattice site
rightward), both running over [0,10) — a legal rigid translation.
defdemoCtx
def demoCtx : SystemCtx
The worked system context.
example(example)
example : checkAll baseInvariants demoCtx = true
example(example)
example : checkAll (baseInvariants ++ [neutralAtomRigidMoveInv]) demoCtx
= (checkAll baseInvariants demoCtx && neutralAtomRigidMoveInv.check demoCtx)example(example)
example : neutralAtomRigidMoveInv.check demoCtx = true
example(example)
example : checkAll (baseInvariants ++ [neutralAtomRigidMoveInv]) demoCtx = true
defbadMoveCtx
def badMoveCtx : SystemCtx
NEGATIVE: two overlapping moves with DIFFERENT displacement. Move 0
displaces (0,+1); move 1 displaces (+1,0); both run over [0,10), so they
overlap with unequal displacement — a non-rigid (illegal) parallel move.
example(example)
example : neutralAtomRigidMoveInv.check badMoveCtx = false
example(example)
example : checkAll (baseInvariants ++ [neutralAtomRigidMoveInv]) badMoveCtx = false
example(example)
example : checkAll baseInvariants badMoveCtx = true
FormalRV.System.Invariants.ScheduleInvariantsExplicit
FormalRV/System/Invariants/ScheduleInvariantsExplicit.lean
FormalRV.System.Invariants.ScheduleInvariantsExplicit — general decidable
checkers (namespace `FormalRV.System.ScheduleInv`) for the four system-level
invariants of the qianxu (Cain–Xu et al. 2026) system layer.
Each invariant has a corresponding `*_ok` function below.
Inputs are completely explicit: an architecture zone breakdown,
a list of `SysCall`s, and a few scalar bounds. Outputs are
`Bool` (decidable). The user can apply them to any concrete
schedule and discharge via `decide`.
## The four invariants (qianxu system layer)
**I1 capacity**:
∀ t, ∀ zone role ρ, |claimed_t ∩ slots_ρ| ≤ |slots_ρ|
For every cycle `t` and every zone role ρ, the number of
physical atoms claimed by active `SysCall`s at `t` whose
zone has role ρ does not exceed the total atoms of role ρ.
**I2 exclusivity**:
∀ t, ∀ distinct c₁, c₂ ∈ sched(t), slots(c₁) ∩ slots(c₂) = ∅
For every cycle `t`, any two distinct `SysCall`s active at
`t` claim disjoint atoms.
**I3 speed-limit / latency**:
∀ (route c), duration(c) ≥ distance(c) / v_max
∀ (feedback c), latency(c) ≤ t_cycle
Atom transports respect v_max, feedback completes within
one stab cycle.
**I4 throughput**:
∀ t₀, ∀ W, Σ_{t ∈ [t₀, t₀+W)} magicReq(t) ≤ supply(t₀, W)
Over any window of W cycles, the cumulative magicReq
demand does not exceed the factory's CCZ-state supply.
## Decidability strategy
The schedule is a FINITE list of `SysCall`s (each with explicit
`begin_us`, `end_us`, `kind`). Each invariant reduces to:
I1: every claimed atom lies in some zone (linear-in-atoms),
plus a per-cycle per-zone aggregate sampled at begin times
(sound for the MAX bound; see `capacity_per_cycle_ok`).
I2: pairwise over syscalls (O(n²)) — for each pair, if time
intervals overlap, check atom-list disjointness.
I3: per-syscall check on `feedback`/`route`/`decode` syscalls.
I4: per-window check over windows aligned at `magicReq`
begin times. An unaligned window contains a SUBSET of the
magicReqs of some aligned window, so aligned windows
suffice for the ≤-bound.
All four are linear-or-quadratic in the schedule length;
`decide` closes for schedules with ~100s of syscalls.
No Mathlib dependency. Pure Bool / Nat.
structureArchZone
structure ArchZone
An architecture zone described as a contiguous atom range
with a role label. `[site_lo, site_hi)` defines the zone's
atoms; `capacity = site_hi − site_lo`.
structureZonedArch
structure ZonedArch
A zoned architecture: list of disjoint ArchZones covering
the atom-id range `[0, total_sites)` (possibly with gaps).
defzone_of
def zone_of (arch : ZonedArch) (a : Nat) : Option ArchZone
Find the zone containing the given atom (the first match).
defcapacity_in_arch_ok
def capacity_in_arch_ok (arch : ZonedArch) (sched : List SysCall) : Bool
*I1 capacity check.** Every physical atom claimed by any
`SysCall` in the schedule lies inside SOME architecture
zone (i.e., the schedule does not claim atoms outside the
architecture).
For sequential schedules — where at most one syscall is
active at any cycle — this implies the per-cycle per-zone
capacity holds (each zone's load is at most one syscall's
claim ≤ zone capacity). For parallel schedules, we also
check per-cycle per-zone aggregate below
(`capacity_per_cycle_ok`).
defcapacity_per_cycle_ok
def capacity_per_cycle_ok (arch : ZonedArch) (sched : List SysCall) : Bool
*I1 capacity, per-cycle.** For every begin-time t of any
syscall, count the atoms claimed across all simultaneously-
active syscalls by zone, and require each zone's count to
not exceed its capacity.
Decidable: we enumerate the begin-times in the schedule.
Between two consecutive begin-times syscalls can only END,
so the active set at any in-between time is a SUBSET of the
active set at the nearest preceding begin-time. Per-zone
loads are therefore maximised at begin times, and sampling
them is sound for this ≤-capacity bound (it would NOT be
sound for properties of the exact active set).
defexclusivity_ok
def exclusivity_ok (sched : List SysCall) : Bool
*I2 exclusivity check.** For every pair `(i, j)` of distinct
positions in the schedule, if syscalls `i` and `j` overlap in
time, their claimed atoms are disjoint.
deffeedback_latency_ok
def feedback_latency_ok (t_cycle_us : Nat) (sched : List SysCall) : Bool
*I3 feedback-latency check.** Every `PauliFrameUpdate`
syscall completes within one stabilizer cycle.
defspeed_limit_ok
def speed_limit_ok (v_max_um_per_us : Nat)
(distance_fn : Nat → Nat) (sched : List SysCall) : Bool*I3 speed-limit check.** Every `TransitQubit` syscall
satisfies `duration · v_max ≥ distance`.
Note: the existing `TransitQubit q c` SysCall doesn't carry
an explicit `distance` field; the caller supplies it via
`distance_fn` indexed by channel id `c`. For schedules with
NO transits (static architectures like our cuccaro CCZ demo),
this check is vacuously true.
defdecoder_react_ok
def decoder_react_ok (t_react_us : Nat) (sched : List SysCall) : Bool
*I3 decoder-reaction-time check.** Every `DecodeSyndrome`
syscall completes within `t_react_us` µs (the architecture's
decoder reaction budget). Without this, the decoder cannot
catch up with the per-cycle syndrome stream. Decidable
counterpart of the reaction-time clause of
`Architecture.latency_ok : Prop`.
deflatency_speed_ok
def latency_speed_ok (t_cycle_us v_max_um_per_us : Nat)
(distance_fn : Nat → Nat) (sched : List SysCall) : BoolCombined I3: feedback latency AND transit speed-limit AND
decoder reaction-time.
deflatency_speed_decoder_ok
def latency_speed_decoder_ok
(t_cycle_us v_max_um_per_us t_react_us : Nat)
(distance_fn : Nat → Nat) (sched : List SysCall) : BoolStrengthened I3 that ALSO requires the decoder reaction-time
check. `t_react_us` is supplied separately because `ZonedArch`
only carries `t_cycle_us`; the caller passes the architecture's
`t_react_us` field.
defmagicReq_count_in_window
def magicReq_count_in_window (sched : List SysCall) (t0 window : Nat) : Nat
Count `magicReq` syscalls whose `begin_us` falls inside
`[t0, t0 + window)`.
defwindow_throughput_ok
def window_throughput_ok (sched : List SysCall)
(window_us max_per_window : Nat) : Bool*I4 window-throughput check.** For every window `[t0, t0 + window_us)`
aligned with a magicReq's `begin_us`, the number of
magicReqs inside the window does not exceed
`max_per_window`.
Decidable: we enumerate t0 over the magicReq begin times.
Windows not aligned with a magicReq begin contain a SUBSET
of magicReqs of some aligned window, so this is sufficient.
For qianxu's factory (1 CCZ per 12_000 µs distillation
cycle), set `window_us = 12_000` and `max_per_window = 1`.
defsyndrome_bits_in_window
def syndrome_bits_in_window (bits_per_measure : Nat) (sched : List SysCall)
(t0 window_us : Nat) : NatTotal syndrome bits injected by measurements BEGINNING in
`[t0, t0 + window_us)`.
defsyndrome_bandwidth_ok
def syndrome_bandwidth_ok (bits_per_measure window_us max_bits : Nat)
(sched : List SysCall) : Bool*I5 syndrome-bandwidth check.** Every measurement-anchored window
carries at most `max_bits` of syndrome data.
defmeasures_done_by
def measures_done_by (sched : List SysCall) (t : Nat) : Nat
Measures whose intervals ended at or before `t`.
defdecodes_begun_by
def decodes_begun_by (sched : List SysCall) (t : Nat) : Nat
Decodes that begin at or before `t` (ties included).
defsyndrome_causality_ok
def syndrome_causality_ok (sched : List SysCall) : Bool
*I6.a — syndrome measurement finishes BEFORE decode.**
defmagic_begun_by
def magic_begun_by (sched : List SysCall) (t : Nat) : Nat
Magic requests that begin at or before `t` (ties included).
defmagic_available_by
def magic_available_by (initial period per t : Nat) : Nat
States available by `t`: initial stock + the factory production
curve (batch k completes — is fully PREPARED — at time `k·period`).
defmagic_supply_ok
def magic_supply_ok (initial period per : Nat) (sched : List SysCall) : Bool
*I6.b — magic state prepared BEFORE consumed.**
defall_invariants_ok
def all_invariants_ok
(arch : ZonedArch)
(sched : List SysCall)
(window_us max_per_window : Nat)
(distance_fn : Nat → Nat) : BoolThe four-invariant headline checker. Takes everything the
framework needs:
the zoned architecture,
the schedule,
factory window parameters (window_us, max_per_window),
a route distance function (or zero for no-transit).
I3 is enforced in full: feedback latency + transit speed (`latency_speed_ok`) **and** decoder
reaction time (`decoder_react_ok arch.t_react_us`). The reaction budget lives in the
architecture (`ZonedArch.t_react_us`), so a decode slower than the budget is rejected here
without any separate `decoder_react_ok` call by the user.
FormalRV.System.Invariants.SystemInvariantStrengthening
FormalRV/System/Invariants/SystemInvariantStrengthening.lean
FormalRV.System.Invariants.SystemInvariantStrengthening — strengthened
decidable invariant bundles closing gaps documented by the system-checker
review (namespace `FormalRV.System.SystemInvariantStrengthening`).
`Checkers/SystemChecker.lean` documents abstraction gaps in the
strengthened bundle `all_invariants_with_factory_ports_ok`
(`Compile/LatticeSurgeryPPMContract.lean`), each paired with a tiny
counterexample schedule whose acceptance is proven by `native_decide`.
This file closes four of those gaps, as a chain of strictly-stronger
sibling bundles (every older bundle remains available unchanged):
1. **Operation capacity** (§1–§4): `OperationCapacityModel` +
`operation_capacity_ok` — independent per-kind caps on
simultaneously-active operations (e.g. at most 1 parallel `Gate2q`),
which neither site/zone capacity nor exclusivity bounds.
2. **Feedback-after-decode causality** (§5, review §4):
`feedback_after_decode_ok` — every `PauliFrameUpdate cid` must be
preceded by a completed matching `DecodeSyndrome cid`.
→ bundle `all_invariants_strict_ok` (§6).
3. **Per-zone slot capacity** (§11): `SlotCapacityModel` +
`slot_capacity_ok` — caps on simultaneously-active site claims per
zone, independent of the zone's site range.
→ bundle `all_invariants_strict_with_slot_capacity_ok` (§13).
4. **Ancilla freshness/reset lifecycle** (§14, review §6):
`ancilla_freshness_ok` — a Free/Live/Dirty state machine enforcing
allocate → use → measure → re-allocate, no dangling Live.
→ bundle `all_invariants_strict_with_slot_capacity_and_freshness_ok`
(§16).
Each repair carries FAILURE-ISOLATION theorems: the new check rejects a
schedule the previous bundle provably accepts, and the known-good compiled
stream (`compileSurgeryGadgetToSysCalls surgery_ppm_A`) still passes every
bundle.
## Remaining review gaps (open; regression theorems preserved, see §10)
`target_pauli` ignored by the topology compiler (review §3);
routing-lane / coupler exclusivity for `Gate2q` (review §5);
`SiteId` / `FactoryPortId` type-level partition (review §7);
factory causal-supply prefix (review §8).
## Platform-neutral terminology
All new identifiers use **site / physical resource /
operation capacity / routing lane / factory port / decoder
channel**. No new generic identifier uses "atom". Legacy
fields like `total_sites`, `contains_atom`, `syscall_acts_on`
appear only as references to pre-existing names; read them as
site / physical-resource ids.
No Mathlib. No `sorry`. No custom `axiom`. Pure Bool / Nat.
Decidable; `native_decide` closes all examples.
structureOperationCapacityModel
structure OperationCapacityModel
defscheduleEventTimes
def scheduleEventTimes (sched : List SysCall) : List Nat
Distinct begin-times encountered in the schedule. We don't
dedupe — `List.all` over duplicates is still correct, just
slower.
defcountActiveKindAt
def countActiveKindAt
(predicate : SysCallKind → Bool) (t : Nat) (sched : List SysCall) : NatCount SysCalls of the given kind active at time `t`.
defoperation_capacity_ok
def operation_capacity_ok
(cap : OperationCapacityModel) (sched : List SysCall) : Bool*Headline operation-capacity check.** Enforces independent
operation-kind caps.
deffeedback_after_decode_ok
def feedback_after_decode_ok (sched : List SysCall) : Bool
*Feedback-after-decode causal check.**
defall_invariants_strict_ok
def all_invariants_strict_ok
(arch : ZonedArch)
(cap : OperationCapacityModel)
(sched : List SysCall)
(t_react_us window_us max_per_window : Nat) : Bool*The strict bundle.** Strictly stronger than
`all_invariants_with_factory_ports_ok`: adds the
operation-capacity check and the feedback-after-decode
check.
defdemo_arch
def demo_arch : ZonedArch
Demo architecture — alias for the existing
`surgery_arch` (4 zones × 100 sites = 400 sites).
defdemo_t_react
def demo_t_react : Nat
Demo decoder-react budget.
defdemo_window
def demo_window : Nat
Demo throughput window.
defdemo_max_per_window
def demo_max_per_window : Nat
Demo throughput cap.
defdemo_operation_cap
def demo_operation_cap : OperationCapacityModel
Demo operation cap with TIGHT `max_gate2q_active = 1` (the
rest are slack so they don't accidentally fire). This is
the cap that catches the review's parallel-Gate2q gap.
defoperation_capacity_good_schedule
def operation_capacity_good_schedule : List SysCall
Two SEQUENTIAL `Gate2q` calls on the same pair of sites.
Each is active alone; max concurrency = 1. Should pass
`operation_capacity_ok` under `max_gate2q_active = 1`.
theoremoperation_capacity_good_ok
theorem operation_capacity_good_ok :
operation_capacity_ok demo_operation_cap
operation_capacity_good_schedule = truedefoperation_capacity_bad_parallel_gates
def operation_capacity_bad_parallel_gates : List SysCall
Two PARALLEL `Gate2q` calls on ENDPOINT-DISJOINT sites.
The old `exclusivity_ok` PASSES (atoms `[0,1]` and `[2,3]`
are disjoint); `operation_capacity_ok` REJECTS because two
Gate2qs are simultaneously active.
theoremoperation_capacity_bad_parallel_gates_fails
theorem operation_capacity_bad_parallel_gates_fails :
operation_capacity_ok demo_operation_cap
operation_capacity_bad_parallel_gates = falsetheoremoperation_capacity_bad_parallel_gates_old_bundle_passes
theorem operation_capacity_bad_parallel_gates_old_bundle_passes :
all_invariants_with_factory_ports_ok
demo_arch operation_capacity_bad_parallel_gates
demo_t_react demo_window demo_max_per_window = truedeffeedback_after_decode_good_schedule
def feedback_after_decode_good_schedule : List SysCall
A schedule where `DecodeSyndrome 0` finishes at t=5 and
`PauliFrameUpdate 0` starts at t=5. Causal ordering
satisfied (end ≤ begin).
theoremfeedback_after_decode_good_ok
theorem feedback_after_decode_good_ok :
feedback_after_decode_ok feedback_after_decode_good_schedule = truetheoremdecoder_dependency_violator_now_rejected
theorem decoder_dependency_violator_now_rejected :
feedback_after_decode_ok decoder_dependency_violator = false*Review fix verified**: the review's
`decoder_dependency_violator` (PauliFrameUpdate at t=0
BEFORE matching DecodeSyndrome at t=10) is now REJECTED
by `feedback_after_decode_ok`.
deffeedback_orphan_schedule
def feedback_orphan_schedule : List SysCall
A schedule with PauliFrameUpdate referencing a channel id
that has NO matching DecodeSyndrome anywhere — also
rejected.
theoremfeedback_orphan_rejected
theorem feedback_orphan_rejected :
feedback_after_decode_ok feedback_orphan_schedule = falsetheoremstrict_rejects_operation_capacity_bad
theorem strict_rejects_operation_capacity_bad :
all_invariants_strict_ok demo_arch demo_operation_cap
operation_capacity_bad_parallel_gates
demo_t_react demo_window demo_max_per_window = falsetheoremstrict_rejects_decoder_dependency_violator
theorem strict_rejects_decoder_dependency_violator :
all_invariants_strict_ok demo_arch demo_operation_cap
decoder_dependency_violator
demo_t_react demo_window demo_max_per_window = falsetheoremstrict_accepts_surgery_ppm_A
theorem strict_accepts_surgery_ppm_A :
all_invariants_strict_ok demo_arch demo_operation_cap
(compileSurgeryGadgetToSysCalls surgery_ppm_A)
demo_t_react demo_window demo_max_per_window = truedefhigh_parallel_operation_cap
def high_parallel_operation_cap : OperationCapacityModel
A "high-parallelism" operation cap that mirrors hardware
with > 1 simultaneous Gate2q support. Used to expose the
residual routing-lane gap: with `max_gate2q_active = 10`,
the operation-capacity check does NOT catch a routing-lane
conflict between two parallel Gate2qs.
theoremstrict_still_accepts_routing_lane_violator
theorem strict_still_accepts_routing_lane_violator :
all_invariants_strict_ok demo_arch high_parallel_operation_cap
routing_lane_violator
demo_t_react demo_window demo_max_per_window = true*Open-gap regression**: the strict bundle still accepts the
review's `routing_lane_violator` because operation-capacity
bounds GATE-KIND count, not coupler-lane occupancy. Under
`demo_operation_cap` (`max_gate2q_active = 1`), the strict
bundle ACCIDENTALLY rejects this — not because of routing
lanes but because of gate count — so we use
`high_parallel_operation_cap` to keep the regression
meaningful. Closing this gap properly needs a routing-lane
resource model.
theoremstrict_still_accepts_freshness_use_before_reset
theorem strict_still_accepts_freshness_use_before_reset :
all_invariants_strict_ok demo_arch demo_operation_cap
freshness_use_before_reset
demo_t_react demo_window demo_max_per_window = true*Isolation**: the plain strict bundle accepts
`freshness_use_before_reset` — it has no lifecycle state
machine. The gap is closed by `ancilla_freshness_ok` (§14);
see §16.a for the rejection by the freshness bundle.
theoremstrict_still_accepts_magic_no_startup_prefix
theorem strict_still_accepts_magic_no_startup_prefix :
all_invariants_strict_ok demo_arch demo_operation_cap
magic_no_startup_prefix
demo_t_react demo_window 1 = true*Open-gap regression**: the strict bundle still accepts
`magic_no_startup_prefix` (window throughput is aggregate,
not causal prefix).
structureZoneCapacitySpec
structure ZoneCapacitySpec
A slot-capacity zone spec. Independent of `ArchZone`:
carries its own site-interval `[site_lo, site_hi)` and a
`slot_capacity` upper bound on the number of
simultaneously-active site claims inside that interval.
The `zone_id : Nat` field is the stable numeric identifier
that `ArchZone` lacks; it is used only for documentation /
error reporting on the spec side.
structureSlotCapacityModel
structure SlotCapacityModel
A slot-capacity model: a list of zone specs. Multiple
specs may overlap in their site intervals (e.g., a
coarse-grained zone PLUS a finer-grained sub-zone), in
which case all overlapping specs must pass — strictly
cumulative semantics.
defactiveSitesAt
def activeSitesAt (t : Nat) (sched : List SysCall) : List Nat
All site occurrences claimed by syscalls active at time
`t`. Uses the existing `syscall_acts_on` helper from
`CodedLayout.lean`; factory-port claims are NOT included
here (they are handled by `factory_exclusivity_ok` in the
old bundle). Count is occurrence-based; under
`exclusivity_ok` (already in the strict bundle), the count
equals the count of distinct claimed sites.
defactiveSiteCountInZoneAt
def activeSiteCountInZoneAt
(z : ZoneCapacitySpec) (t : Nat) (sched : List SysCall) : NatCount of active site claims falling inside the spec's
interval at time `t`.
defslot_capacity_ok
def slot_capacity_ok
(slotCap : SlotCapacityModel) (sched : List SysCall) : Bool*Headline slot-capacity check.** At every sampled begin
time, every zone spec's active site-count must not exceed
its declared `slot_capacity`.
defslot_capacity_demo_arch
def slot_capacity_demo_arch : ZonedArch
Demo architecture for the slot-capacity examples. Two
zones, 100 sites each. Legacy `site_lo/site_hi` fields
carry the site-interval bounds.
defslot_capacity_demo_model
def slot_capacity_demo_model : SlotCapacityModel
Demo slot-capacity model. The data zone supports only 2
simultaneous active site claims; the ancilla zone is
generous (100).
defslot_capacity_good_schedule
def slot_capacity_good_schedule : List SysCall
Two simultaneous `Gate1q`s on data sites 0 and 1. Two
active sites in data zone (slot_cap=2). Passes.
theoremslot_capacity_good_ok
theorem slot_capacity_good_ok :
slot_capacity_ok slot_capacity_demo_model
slot_capacity_good_schedule = truedefslot_capacity_bad_three_active_sites
def slot_capacity_bad_three_active_sites : List SysCall
Three parallel `Gate1q`s on data sites 0, 1, 2. All in
data zone (slot_cap=2). Fails.
theoremslot_capacity_bad_three_active_sites_fails
theorem slot_capacity_bad_three_active_sites_fails :
slot_capacity_ok slot_capacity_demo_model
slot_capacity_bad_three_active_sites = falsetheoremslot_capacity_bad_old_capacity_passes
theorem slot_capacity_bad_old_capacity_passes :
capacity_in_arch_ok slot_capacity_demo_arch
slot_capacity_bad_three_active_sites = truetheoremslot_capacity_bad_capacity_per_cycle_passes
theorem slot_capacity_bad_capacity_per_cycle_passes :
capacity_per_cycle_ok slot_capacity_demo_arch
slot_capacity_bad_three_active_sites = truetheoremslot_capacity_bad_exclusivity_passes
theorem slot_capacity_bad_exclusivity_passes :
exclusivity_ok slot_capacity_bad_three_active_sites = truetheoremslot_capacity_bad_operation_capacity_passes
theorem slot_capacity_bad_operation_capacity_passes :
operation_capacity_ok high_parallel_operation_cap
slot_capacity_bad_three_active_sites = truedefall_invariants_strict_with_slot_capacity_ok
def all_invariants_strict_with_slot_capacity_ok
(arch : ZonedArch)
(opCap : OperationCapacityModel)
(slotCap : SlotCapacityModel)
(sched : List SysCall)
(t_react_us window_us max_per_window : Nat) : Bool*The strict-with-slot-capacity bundle.** Strictly
stronger than `all_invariants_strict_ok`: adds
`slot_capacity_ok`.
theoremstrict_with_slot_capacity_rejects_bad_three_active_sites
theorem strict_with_slot_capacity_rejects_bad_three_active_sites :
all_invariants_strict_with_slot_capacity_ok
slot_capacity_demo_arch
high_parallel_operation_cap
slot_capacity_demo_model
slot_capacity_bad_three_active_sites
demo_t_react demo_window demo_max_per_window = false*The new bundle rejects the bad slot-capacity schedule.**
theoremstrict_without_slot_capacity_accepts_bad_three_active_sites
theorem strict_without_slot_capacity_accepts_bad_three_active_sites :
all_invariants_strict_ok
slot_capacity_demo_arch
high_parallel_operation_cap
slot_capacity_bad_three_active_sites
demo_t_react demo_window demo_max_per_window = true*The PREVIOUS strict bundle ACCEPTS the bad slot-capacity
schedule** — formal evidence that slot capacity is a
distinct repair beyond operation capacity.
defgenerous_slot_capacity_model
def generous_slot_capacity_model : SlotCapacityModel
Generous slot-capacity model matching `surgery_arch`: 100
slots per zone, the full site interval.
theoremstrict_with_slot_capacity_accepts_surgery_ppm_A
theorem strict_with_slot_capacity_accepts_surgery_ppm_A :
all_invariants_strict_with_slot_capacity_ok
surgery_arch demo_operation_cap generous_slot_capacity_model
(compileSurgeryGadgetToSysCalls surgery_ppm_A)
demo_t_react demo_window demo_max_per_window = trueinductiveSiteLifecycle
inductive SiteLifecycle
The three lifecycle states a tracked ancilla site can
inhabit.
structureAncillaZoneSpec
structure AncillaZoneSpec
An ancilla zone spec: identifies a `target_zone` id and
its `[site_lo, site_hi)` interval. Independent of
`ArchZone`/`ZoneCapacitySpec` to keep this module
self-contained.
structureAncillaModel
structure AncillaModel
A lifecycle model: which `target_zone`s the freshness
checker is responsible for. Sites outside every spec's
range are treated as data sites and not lifecycle-tracked.
deflifecycleOf
def lifecycleOf
(state : List (Nat × SiteLifecycle)) (site : Nat) : SiteLifecycleLookup a site's current lifecycle; defaults `Free`.
defsetLifecycle
def setLifecycle
(state : List (Nat × SiteLifecycle))
(site : Nat) (lc : SiteLifecycle) : List (Nat × SiteLifecycle)Set a site's lifecycle; updates an existing entry or
appends if absent.
defsiteInAncillaModel
def siteInAncillaModel (model : AncillaModel) (site : Nat) : Bool
Is the given site inside any of the model's ancilla
zones?
deffreshnessStep
def freshnessStep
(model : AncillaModel)
(state : List (Nat × SiteLifecycle)) (sc : SysCall) :
Option (List (Nat × SiteLifecycle))One step of the freshness state machine. Returns
`some state'` on success, `none` on lifecycle violation.
defrunFreshness
def runFreshness
(model : AncillaModel) (state : List (Nat × SiteLifecycle)) :
List SysCall → Option (List (Nat × SiteLifecycle))
| [] => some state
| sc :: rest =>
match freshnessStep model state sc with
| none => none
| some state' => runFreshness model state' restWalk the schedule's SysCalls in list order, threading
the lifecycle state. Returns `none` on the first
lifecycle violation.
defnoDanglingLive
def noDanglingLive (state : List (Nat × SiteLifecycle)) : Bool
Predicate: no site in the final state is `Live`
(every allocated ancilla has been measured or never
allocated).
defancilla_freshness_ok
def ancilla_freshness_ok
(model : AncillaModel) (sched : List SysCall) : Bool*Headline freshness check.** Walks the schedule in
list order under the given `AncillaModel`; rejects if
any step violates the lifecycle OR if the final state
has a dangling `Live` site.
Note: assumes the schedule is already chronologically
ordered by `begin_us`. All schedules emitted by the
framework's compilers
(`compileSurgeryGadgetToSysCalls`,
`compileTopologySurgeryToSysCalls`,
`ppm_block_syscalls`) satisfy this.
defdemo_ancilla_model
def demo_ancilla_model : AncillaModel
The demo `AncillaModel`: one tracked zone, sites
`[100, 200)`. Matches `surgery_arch`'s Ancilla zone; the
compilers request their spec's explicit `ancilla_site`.
theoremfreshness_use_before_reset_now_rejected
theorem freshness_use_before_reset_now_rejected :
ancilla_freshness_ok demo_ancilla_model
freshness_use_before_reset = false*Review fix verified**: `freshness_use_before_reset`
(Gate2q on site 100 BEFORE any `RequestFreshAncilla`) is
now REJECTED — the step function fails at the first
`Gate2q` because site 100's default lifecycle is
`Free`.
theoremfreshness_reuse_without_reset_now_rejected
theorem freshness_reuse_without_reset_now_rejected :
ancilla_freshness_ok demo_ancilla_model
freshness_reuse_without_reset = false*Review fix verified**: `freshness_reuse_without_reset`
(one allocation, two Gate2qs, no Measure) is now
REJECTED by the dangling-Live rule — site 100 ends
`Live` because no `Measure` consumed it.
deffreshness_reuse_after_measure
def freshness_reuse_after_measure : List SysCall
Reuse-after-Measure without a fresh allocation: site 100
is measured (→ Dirty), then a Gate2q targets it again
without `RequestFreshAncilla`. Rejected at the second
Gate2q.
theoremfreshness_reuse_after_measure_rejected
theorem freshness_reuse_after_measure_rejected :
ancilla_freshness_ok demo_ancilla_model
freshness_reuse_after_measure = falsedeffreshness_orphan_measure
def freshness_orphan_measure : List SysCall
Orphan Measure: ancilla site 100 is measured with no
prior `RequestFreshAncilla`. Rejected.
theoremfreshness_orphan_measure_rejected
theorem freshness_orphan_measure_rejected :
ancilla_freshness_ok demo_ancilla_model
freshness_orphan_measure = falsedeffreshness_one_slot_model
def freshness_one_slot_model : AncillaModel
Double allocation: two `RequestFreshAncilla 100` calls on
the SAME explicit site with no intervening Measure — the
second request finds site 100 `Live` and is rejected
directly (with explicit sites, no zone-exhaustion detour
is needed).
deffreshness_double_alloc
def freshness_double_alloc : List SysCall
theoremfreshness_double_alloc_rejected
theorem freshness_double_alloc_rejected :
ancilla_freshness_ok freshness_one_slot_model
freshness_double_alloc = falsedeffreshness_good_short
def freshness_good_short : List SysCall
A minimal valid PPM-shape sequence: Request site 100,
Gate2q, Measure. Site 100 ends `Dirty`.
theoremfreshness_good_short_ok
theorem freshness_good_short_ok :
ancilla_freshness_ok demo_ancilla_model
freshness_good_short = truetheoremancilla_freshness_accepts_surgery_ppm_A
theorem ancilla_freshness_accepts_surgery_ppm_A :
ancilla_freshness_ok demo_ancilla_model
(compileSurgeryGadgetToSysCalls surgery_ppm_A) = true*The simple compiler's basic PPM output stays
accepted**: every round emits Request → Live, two
Gate2qs (allowed, ancilla stays Live), Measure → Dirty;
next round re-allocates the same site. End state:
Dirty. No dangling Live.
defall_invariants_strict_with_slot_capacity_and_freshness_ok
def all_invariants_strict_with_slot_capacity_and_freshness_ok
(arch : ZonedArch)
(opCap : OperationCapacityModel)
(slotCap : SlotCapacityModel)
(model : AncillaModel)
(sched : List SysCall)
(t_react_us window_us max_per_window : Nat) : Bool*The strict-with-slot-capacity-and-freshness bundle.**
Strictly stronger than
`all_invariants_strict_with_slot_capacity_ok`.
theoremstrict_with_freshness_rejects_use_before_reset
theorem strict_with_freshness_rejects_use_before_reset :
all_invariants_strict_with_slot_capacity_and_freshness_ok
demo_arch demo_operation_cap generous_slot_capacity_model
demo_ancilla_model freshness_use_before_reset
demo_t_react demo_window demo_max_per_window = falsetheoremstrict_with_freshness_rejects_reuse_without_reset
theorem strict_with_freshness_rejects_reuse_without_reset :
all_invariants_strict_with_slot_capacity_and_freshness_ok
demo_arch demo_operation_cap generous_slot_capacity_model
demo_ancilla_model freshness_reuse_without_reset
demo_t_react demo_window demo_max_per_window = falsetheoremstrict_with_freshness_rejects_reuse_after_measure
theorem strict_with_freshness_rejects_reuse_after_measure :
all_invariants_strict_with_slot_capacity_and_freshness_ok
demo_arch demo_operation_cap generous_slot_capacity_model
demo_ancilla_model freshness_reuse_after_measure
demo_t_react demo_window demo_max_per_window = falsetheoremstrict_with_slot_capacity_accepts_freshness_use_before_reset
theorem strict_with_slot_capacity_accepts_freshness_use_before_reset :
all_invariants_strict_with_slot_capacity_ok
demo_arch demo_operation_cap generous_slot_capacity_model
freshness_use_before_reset
demo_t_react demo_window demo_max_per_window = truetheoremstrict_with_slot_capacity_accepts_freshness_reuse_without_reset
theorem strict_with_slot_capacity_accepts_freshness_reuse_without_reset :
all_invariants_strict_with_slot_capacity_ok
demo_arch demo_operation_cap generous_slot_capacity_model
freshness_reuse_without_reset
demo_t_react demo_window demo_max_per_window = truetheoremstrict_with_freshness_accepts_surgery_ppm_A
theorem strict_with_freshness_accepts_surgery_ppm_A :
all_invariants_strict_with_slot_capacity_and_freshness_ok
surgery_arch demo_operation_cap generous_slot_capacity_model
demo_ancilla_model
(compileSurgeryGadgetToSysCalls surgery_ppm_A)
demo_t_react demo_window demo_max_per_window = trueFormalRV.System.Magic.MagicScheduleComplete
FormalRV/System/Magic/MagicScheduleComplete.lean
FormalRV.System.MagicScheduleComplete — the WHOLE-CIRCUIT magic-aware device schedule:
latency + qubit cost + routing + waiting, considered together.
Building on `MagicStateReadiness` (which models one magic state's produce→route→consume
pipeline and the "wait if not ready" law), this file lifts the law to the WHOLE circuit:
**Waiting (whole circuit).** `respectsReadiness` — NO magic-consuming gate fires before its
magic is produced and routed. With `F` pipelined factories the i-th magic state is ready at
`pipelinedReadyTime i`, and the `waitingSchedule` (every gate fires exactly when its magic is
ready) provably respects readiness; a premature schedule provably violates it.
**Latency.** Each gate's earliest fire time carries the full `deliveryLatency`
(`production_us` + routing) plus its position in the factory pipeline.
**Qubit cost (whole device).** `deviceQubits = data + factory + routing` — the surface-code
data patches, the magic-state-factory footprint (derived from the throughput requirement),
and the routing/ancilla overhead, summed.
**Routing.** Readiness requires a `TransitQubit` (Factory→Processor) between production and
consumption; the routing latency is inside `deliveryLatency`.
Headline: `windowed_rsa2048_device_schedule_ok` bundles, for the windowed RSA-2048 circuit at the
Gidney–Ekerå hardware parameters with CCZ factories sized for the 8-hour budget: a readiness-
respecting (waiting) schedule exists, the runtime is magic-pipeline-bounded UNDER an assumed
magic-limited hypothesis, and the device qubit budget decomposes as data + factory + routing.
Concrete numbers use the paper-cited `ccz_spec_qianxu` and the canonical workload constants in
`Params/RSA2048`; the model is parametric in the `MagicStateSpec`.
defpipelinedReadyTime
def pipelinedReadyTime (i F : Nat) (spec : MagicStateSpec) (routingLatency : Nat) : Nat
With `F` factories pipelined, the `i`-th magic state (0-indexed) is ready at
`deliveryLatency + (i / F)·production_us`: factory `i % F` is on its `(i / F)`-th batch.
defrespectsReadiness
def respectsReadiness (consumeBegin : Nat → Nat) (K F : Nat)
(spec : MagicStateSpec) (lat : Nat) : BoolA consume-time assignment `consumeBegin : gateIndex → time` RESPECTS readiness for `K`
magic-consuming gates iff every gate `i` fires no earlier than its magic is ready.
defwaitingSchedule
def waitingSchedule (F : Nat) (spec : MagicStateSpec) (lat : Nat) : Nat → Nat
The "always-wait" schedule: gate `i` fires exactly when its magic becomes ready.
theoremwaitingSchedule_respectsReadiness
theorem waitingSchedule_respectsReadiness (K F : Nat) (spec : MagicStateSpec) (lat : Nat) :
respectsReadiness (waitingSchedule F spec lat) K F spec lat = true*The waiting schedule respects readiness — by construction.** `waitingSchedule` fires gate
`i` exactly at `pipelinedReadyTime i`, so each check is `ready ≤ ready` and the proof is
`decide (x ≤ x)`. The content is existential: a readiness-respecting schedule for all `K`
consumers EXISTS (contrast `premature_violates_readiness`).
theorempremature_violates_readiness
theorem premature_violates_readiness
(consumeBegin : Nat → Nat) (K F : Nat) (spec : MagicStateSpec) (lat : Nat)
(i : Nat) (hi : i < K) (hlt : consumeBegin i < pipelinedReadyTime i F spec lat) :
respectsReadiness consumeBegin K F spec lat = false*A premature schedule violates readiness.** If any gate `i < K` fires before its magic is
ready (`consumeBegin i < pipelinedReadyTime i`), the whole-circuit readiness check fails —
the gate would consume a magic state that is not yet produced/routed.
deffullMagicGateSchedule
def fullMagicGateSchedule (consumeBegin : Nat) : Schedule
A full magic-consuming-gate schedule: the produce→route delivery, then the consumer
`Gate2q (data, magicQubit)` (the teleportation injection) at `consumeBegin`.
defconsumerMagicReady
def consumerMagicReady (sched : Schedule) (consumeBegin magicQubit : Nat) : Bool
The consumer is magic-ready iff some production completed before some routing transit of the
magic qubit, which completed before the consumer fires (produce → route → consume).
theoremconsume_too_early_not_ready
theorem consume_too_early_not_ready :
consumerMagicReady (fullMagicGateSchedule 5000) 5000 100 = false*Premature consumption is caught at the SysCall level.** A gate that fires at 5000 µs — before
the CCZ is produced (12000 µs) and routed (+15 µs) — is NOT magic-ready: it must WAIT.
theoremconsume_after_wait_ready
theorem consume_after_wait_ready :
consumerMagicReady (fullMagicGateSchedule 12015) 12015 100 = trueA gate that waits until 12015 µs (production + routing complete) IS magic-ready.
defcircuitRuntimeUs
def circuitRuntimeUs (logicalDepthUs K F : Nat) (spec : MagicStateSpec) (lat : Nat) : Nat
Whole-circuit wallclock: the maximum of the logical depth and the magic-supply pipeline
(`deliveryLatency + ⌈K/F⌉·production_us`). The circuit waits for whichever is slower.
theoremruntime_magic_limited
theorem runtime_magic_limited
(logicalDepthUs K F : Nat) (spec : MagicStateSpec) (lat : Nat)
(h : logicalDepthUs ≤ deliveryLatency spec lat + magicSupplyTimeUs K F spec) :
circuitRuntimeUs logicalDepthUs K F spec lat
= deliveryLatency spec lat + magicSupplyTimeUs K F spec*Magic-limited regime.** When the magic pipeline exceeds the logical depth (hypothesis `h`),
the runtime IS the magic pipeline. The proof is just `max a b = b` given `a ≤ b` —
`circuitRuntimeUs` is a `Nat.max`; the theorem names the regime, it does not establish that
any particular circuit is in it.
defdeviceQubits
def deviceQubits (dataQubits factoryQubits routingQubits : Nat) : Nat
Total device physical qubits = surface-code data patches + magic-factory footprint
+ routing/ancilla overhead.
defrsa2048_data_qubits
def rsa2048_data_qubits : Nat
Windowed RSA-2048 device parameters at GE2021 hardware (magic budget from the canonical
`Params/RSA2048`; factories/footprint DERIVED from the throughput requirement, not assumed).
defrsa2048_magic_budget
def rsa2048_magic_budget : Nat
defrsa2048_factories
def rsa2048_factories : Nat
defrsa2048_factory_qubits
def rsa2048_factory_qubits : Nat
theoremrsa2048_factories_value
theorem rsa2048_factories_value : rsa2048_factories = 1093
theoremrsa2048_factory_qubits_value
theorem rsa2048_factory_qubits_value : rsa2048_factory_qubits = 2803545
theoremwindowed_rsa2048_device_schedule_ok
theorem windowed_rsa2048_device_schedule_ok (routingQubits logicalDepthUs : Nat)
(h_magic_limited :
logicalDepthUs ≤ deliveryLatency ccz_spec_qianxu 15
+ magicSupplyTimeUs rsa2048_magic_budget 1 ccz_spec_qianxu) :
-- (1) waiting: no premature magic consumption
respectsReadiness (waitingSchedule rsa2048_factories ccz_spec_qianxu 15)
rsa2048_magic_budget rsa2048_factories ccz_spec_qianxu 15 = true
-- (2) magic-limited runtime at one factory: the circuit waits on magic
∧ circuitRuntimeUs logicalDepthUs rsa2048_magic_budget 1 ccz_spec_qianxu 15
= deliveryLatency ccz_spec_qianxu 15
+ magicSupplyTimeUs rsa2048_magic_budget 1 ccz_spec_qianxu
-- (3) device qubit budget = data + factory + routing*★ Whole-device schedule bundle for windowed RSA-2048 at GE2021 hardware ★.** Simultaneously:
(1) **Waiting** — the always-wait schedule over all `K` Toffoli magic consumers respects
readiness. This conjunct holds BY CONSTRUCTION (`waitingSchedule_respectsReadiness`):
its content is that such a schedule exists, not that an arbitrary one complies.
(2) **Magic-limited runtime** — UNDER the assumed hypothesis `h_magic_limited` (the logical
depth is below the single-factory magic pipeline — plausible, since that pipeline exceeds
8 hours by `windowed_single_factory_is_magic_limited`, but not proven for the windowed
circuit here), the single-factory runtime is the magic pipeline; this is why `1093`
parallel factories are sized for the budget.
(3) **Qubit budget** — the device decomposes as data (`9 633 792`) + factory (`2 803 545`)
+ routing; the factory share is derived from the throughput requirement, not assumed.
FormalRV.System.Magic.MagicStateReadiness
FormalRV/System/Magic/MagicStateReadiness.lean
FormalRV.System.MagicStateReadiness — the magic-state system call as a RESOURCE with latency,
qubit footprint, and routing, plus the "wait if not ready" scheduling dependency.
`Architecture` declares `MagicStateSpec` (`production_us` latency, `factory_qubits` footprint,
fidelity) and the `RequestMagicState` / `TransitQubit` SysCalls; this file binds them to
scheduling:
A magic state is PRODUCED in a factory (`RequestMagicState`, lasting `production_us`),
then ROUTED to the processor (`TransitQubit` through a `MagicSupply` channel, lasting the
channel latency). Only AFTER both complete is it READY to inject (`magicReadyAt`).
The wait law: a consumer that fires before the delivery completes finds the state NOT
ready — it must WAIT (`consumeBegin ≥ production_us + routing_latency`).
`factoryFootprint`: each in-flight production occupies `factory_qubits`; concurrent
productions must fit the Factory zone capacity.
`magicSupplyTimeUs` / `factoriesNeeded` / `factoryQubitShare`: from the circuit's magic
budget + a per-factory throughput, the supply time, the number of factories, and hence
the magic share of the device's physical qubits follow.
Concrete numbers use the paper-cited `ccz_spec_qianxu` (`Architecture.lean`); the model is
parametric in the `MagicStateSpec`, so any other factory spec plugs in unchanged.
defdeliveryLatency
def deliveryLatency (spec : MagicStateSpec) (routingLatency : Nat) : Nat
Total latency before a freshly-started magic state is ready to inject: the factory
`production_us` (cultivation/distillation) plus the Factory→Processor routing latency.
defmagicDelivery
def magicDelivery (f cid magicQubit start : Nat) (spec : MagicStateSpec) (routingLatency : Nat) :
ScheduleA concrete magic-delivery sub-schedule starting at `start`: a `RequestMagicState` in factory
zone `f` lasting `spec.production_us`, then a `TransitQubit` of the magic qubit through
MagicSupply channel `cid` lasting `routingLatency`. Models the physical pipeline.
defmagicReadyAt
def magicReadyAt (delivery : Schedule) (t : Nat) : Bool
The magic state is READY at time `t` iff every step of its delivery (production + routing)
has completed by `t`.
theoremmagicReadyAt_magicDelivery
theorem magicReadyAt_magicDelivery
(f cid mq start : Nat) (spec : MagicStateSpec) (lat t : Nat) :
magicReadyAt (magicDelivery f cid mq start spec lat) t
= decide (start + deliveryLatency spec lat ≤ t)*The wait law.** A magic state whose delivery starts at `start` is ready exactly at
`start + production_us + routingLatency` — the full `deliveryLatency`. A consumer that wants
it earlier finds it NOT ready and must WAIT. (Proven by reducing the `all` over the two
delivery steps: the routing end dominates the production end.)
theoremearliest_consume_is_deliveryLatency
theorem earliest_consume_is_deliveryLatency
(f cid mq : Nat) (spec : MagicStateSpec) (lat : Nat) :
magicReadyAt (magicDelivery f cid mq 0 spec lat) (deliveryLatency spec lat) = true
∧ ∀ t, t < deliveryLatency spec lat →
magicReadyAt (magicDelivery f cid mq 0 spec lat) t = false*Earliest legal consume time = the delivery latency.** Restated: the consumer must wait at
least `deliveryLatency` after production starts.
defccz_delivery_demo
def ccz_delivery_demo : Schedule
A CCZ delivery starting at t=0, routed through a 15 µs channel (neutral-atom MagicSupply).
theoremccz_not_ready_at_5000
theorem ccz_not_ready_at_5000 : magicReadyAt ccz_delivery_demo 5000 = false
*WAIT, demonstrated.** A consumer that wants the CCZ at `t = 5000 µs` finds it NOT ready —
production alone takes 12000 µs. The circuit must stall.
theoremccz_not_ready_at_12014
theorem ccz_not_ready_at_12014 : magicReadyAt ccz_delivery_demo 12014 = false
It is still not ready one tick before the full delivery latency …
theoremccz_ready_at_12015
theorem ccz_ready_at_12015 : magicReadyAt ccz_delivery_demo 12015 = true
… and becomes ready exactly at `12015 µs` (12000 production + 15 routing).
deffactoryFootprint
def factoryFootprint (n : Nat) (spec : MagicStateSpec) : Nat
Factory-zone qubits occupied by `n` concurrently-producing magic states of spec `spec`.
deffootprintFits
def footprintFits (n cap : Nat) (spec : MagicStateSpec) : Bool
A Factory zone of capacity `cap` admits at most `cap / factory_qubits` concurrent productions;
asking for more OVER-SUBSCRIBES the zone (a capacity violation).
theoremccz_footprint_one
theorem ccz_footprint_one : factoryFootprint 1 ccz_spec_qianxu = 2565
One CCZ production occupies 2565 physical qubits.
theoremccz_footprint_oversubscription
theorem ccz_footprint_oversubscription :
footprintFits 1 5000 ccz_spec_qianxu = true
∧ footprintFits 3 5000 ccz_spec_qianxu = false*Footprint over-subscription, demonstrated.** Three concurrent CCZ productions need 7695
qubits and do NOT fit a 5000-qubit Factory zone; one does.
defmagicSupplyTimeUs
def magicSupplyTimeUs (K F : Nat) (spec : MagicStateSpec) : Nat
Magic-supply wallclock for `K` states from `F` parallel factories: `⌈K/F⌉ · production_us`.
deffactoriesNeeded
def factoriesNeeded (K budgetUs : Nat) (spec : MagicStateSpec) : Nat
Number of parallel factories needed so the magic supply fits within `budgetUs`:
enough that `⌈K/F⌉ · production_us ≤ budgetUs`, i.e. `F ≥ K · production_us / budgetUs`.
theoremwindowed_single_factory_is_magic_limited
theorem windowed_single_factory_is_magic_limited :
8 * 3600000000 < magicSupplyTimeUs 2622824448 1 ccz_spec_qianxu*The windowed RSA-2048 magic supply is factory-limited.** With a single CCZ factory, the
`2 622 824 448` Toffoli magic states (= `Params/RSA2048.magicBudget`, the paper-formula
windowed CCZ count; the composed-circuit count `2 578 993 152` is bridged in
`System.Compose.VerifiedWorkloadBridge`) take `2 622 824 448 · 12000 µs ≈ 1.0×10⁹ s` — far beyond the 8-hour budget, so the
circuit would WAIT on magic. Hence parallelism is mandatory. The concrete factory count and
qubit share for the 8-hour budget (1093 factories, 2 803 545 qubits) are pinned in
`Magic/MagicScheduleComplete` (`rsa2048_factories_value`, `rsa2048_factory_qubits_value`).
FormalRV.System.Params.HardwareCatalog
FormalRV/System/Params/HardwareCatalog.lean
FormalRV.System.Params.HardwareCatalog — THE single file where every
hardware assumption / architecture parameter set is defined.
## Why this file exists
The System layer is parametric: every checker takes the architecture and
capacity models as ARGUMENTS, so the tool is not tied to any specific
hardware. Before this file, however, the parameter sets themselves were
scattered (demo archs re-typed in several files, two of them verbatim
mirrors). This catalog is now the one place to:
SEE every hardware assumption the repository uses
(§3 the catalog; §4 re-exports of the legacy/platform records);
CONFIGURE a new machine: write one `HardwareSpec` (§1) — every
checker input (`ZonedArch`, `OperationCapacityModel`,
`SlotCapacityModel`, `AncillaModel`, gate table) and the FTQ-VM
backend JSON are DERIVED from it (§2), so Lean proofs and the VM
run from the same definition;
CHECK any schedule on any spec: `checkScheduleOn` (§2.e) is the
generic entry point — total in the spec, so users may set parameters
arbitrarily BEFORE any hardware is fixed;
TRUST that parameters are live: §5 proves the same schedule gets
DIFFERENT verdicts under different specs (reconfigurability is
observable, not aspirational), and §6 pins the scattered legacy
definitions to catalog entries by equality theorems.
## How to add your machine
def myMachine : HardwareSpec :=
{ adder_d3 with name := "my-machine"
gates := [⟨"CNOT", 2, 2, 4⟩, ...] }
#eval checkScheduleOn myMachine mySchedule -- Bool verdict
theorem my_ok : checkScheduleOn myMachine mySchedule = true := by
native_decide
#eval IO.println myMachine.toBackendJson -- the VM backend
Workload constants (RSA-2048 / GE2021) live in `Params/RSA2048.lean`
(imported and re-exported here): workloads are what you RUN, hardware is
what you RUN IT ON.
structureGateSpec
structure GateSpec
One gate the hardware supports: name, duration (µs), qubit arity, and
how many may run simultaneously (control-electronics cap).
structureZoneSpecH
structure ZoneSpecH
One qubit zone: `vm_id` is the FTQ-VM zone identifier (`anc` →
qubits `anc[0]`, …), `lean_name` the display name used in `ZonedArch`;
the zone owns global sites `[site_lo, site_lo + count)`. `tracked`
zones follow the ancilla freshness lifecycle.
structureDecoderSpec
structure DecoderSpec
The classical decoder pool: finite workers, a reaction-time budget
(doubles as the architecture's `t_react_us`), and — VM-side — a finite
job queue.
structureTokenSpec
structure TokenSpec
A token kind the backend stocks/constrains (VM side): initial
inventory and freshness window (`ttl_us = 0` ⇒ never expires).
structureSyndromeSpec
structure SyndromeSpec
The syndrome-stream link contract: each `Measure` injects
`bits_per_measure` bits (hardware fact — 1 hard bit, or e.g. 64 = 8
stabilizers × 8-bit soft data when one op reads out a whole d=3
patch); the link carries at most `max_bits` per `window_us`.
4 KB/ms ⇒ `window_us := 1000, max_bits := 32768`.
structureHardwareSpec
structure HardwareSpec
A complete hardware/architecture parameter set.
defHardwareSpec.wellFormed
def HardwareSpec.wellFormed (s : HardwareSpec) : Bool
Zones are listed in ascending `site_lo` order and gates have positive
durations — the well-formedness a configuration must satisfy.
defHardwareSpec.toZonedArch
def HardwareSpec.toZonedArch (s : HardwareSpec) : ZonedArch
§2.a The zoned architecture (zone ids = list positions).
defHardwareSpec.toOpCap
def HardwareSpec.toOpCap (s : HardwareSpec) : OperationCapacityModel
§2.b Per-kind operation caps. Gate classes take the MIN across the
class's entries (exact when one entry per class).
defHardwareSpec.toSlotCap
def HardwareSpec.toSlotCap (s : HardwareSpec) : SlotCapacityModel
§2.c Per-zone slot capacities (every site of a zone usable).
defHardwareSpec.toAncillaModel
def HardwareSpec.toAncillaModel (s : HardwareSpec) : AncillaModel
§2.d The freshness-tracked ancilla zones.
abbrevGateTable
abbrev GateTable
The gate-support table: name ↦ (duration, arity). Shared shape with
`Codegen/DeviceProgramParse.parseBackend`.
defHardwareSpec.toGateTable
def HardwareSpec.toGateTable (s : HardwareSpec) : GateTable
defgate_support_ok
def gate_support_ok (table : GateTable) (sched : List SysCall) : Bool
Every named gate / measure / ancilla-request in the schedule is
SUPPORTED by the table with matching duration (gate times are hardware
facts). Mirrored by the FTQ-VM's load-time enforcement.
defHardwareSpec.magicInitialStock
def HardwareSpec.magicInitialStock (s : HardwareSpec) : Nat
The backend's initial `MagicState` stock (from the token table).
defcheckScheduleOn
def checkScheduleOn (s : HardwareSpec) (sched : List SysCall) : Bool
§2.e **The generic verdict** — gate support ∧ I5 link bandwidth ∧
I6 causality ∧ the strict invariant bundle, all inputs derived from
the spec. Total in `s`: any configuration may be checked, none is
privileged.
defjsonBool
private def jsonBool (b : Bool) : String
defZoneSpecH.toJson
def ZoneSpecH.toJson (z : ZoneSpecH) : String
defGateSpec.toJson
def GateSpec.toJson (g : GateSpec) : String
defTokenSpec.toJson
def TokenSpec.toJson (t : TokenSpec) : String
defHardwareSpec.toBackendJson
def HardwareSpec.toBackendJson (s : HardwareSpec) : String
Render the spec as the shared FTQ-VM backend JSON.
defstandardGates
def standardGates : List GateSpec
The standard 1-µs gate set used by the surgery/PPM demos:
CNOT (2q, cap 1 — single-laser hardware), H (1q, cap 4),
measurement (cap 4 — decoder-bank width), explicit ancilla reset.
defadder_d3
def adder_d3 : HardwareSpec
*adder_d3 / surgery demo machine** — 4 zones × 100 logical-patch
sites (each a d=3 surface patch), standard 1-µs gates, a 4-worker
decoder with a 10 µs reaction budget. THE spec behind both
`surgery_arch`/`adder_demo_*` (Lean) and
`ftq_vm/backend/examples/adder_d3_backend.json` (VM).
defadder_d3_dualRail
def adder_d3_dualRail : HardwareSpec
Reconfiguration A: dual-rail control — TWO simultaneous CNOTs.
(§5 proves this flips the parallel-adder verdict.)
defadder_d3_zeroReaction
def adder_d3_zeroReaction : HardwareSpec
Reconfiguration B: a decoder with NO reaction budget (0 µs) — every
decode misses. (§5 proves this flips the good adder verdict.)
defadder_d3_tinyQueue
def adder_d3_tinyQueue : HardwareSpec
Reconfiguration C: a tiny 8-slot decoder queue — syndrome bursts
overflow it (the differential corpus exercises this).
defadder_d3_magicStock
def adder_d3_magicStock : HardwareSpec
Reconfiguration D: a stocked magic-state inventory (VM tokens) with
the qianxu demand window (≤ 1 request per 12 000 µs) — used to exhibit
the I4-window check as a Lean-side discipline the VM's causal token
model does not duplicate.
defadder_d3_magicScarce
def adder_d3_magicScarce : HardwareSpec
Reconfiguration D2: a SCARCE magic stock — exactly ONE prepared state
and no factory production. A second consumption is causally
impossible (I6.b; the VM's token ledger rejects it identically:
`MAGIC_SUPPLY`).
defadder_d3_staleDecode
def adder_d3_staleDecode : HardwareSpec
Reconfiguration E: decode-result tokens that EXPIRE after 5 µs — the
VM's token freshness (ttl) catches stale feedforward that Lean's
order-only `feedback_after_decode_ok` accepts.
defadder_d3_strictDecoder
def adder_d3_strictDecoder : HardwareSpec
Reconfiguration F: a STRICT decoder service — 2 workers, each
occupied for the full decode latency (the schedules use 1 ms decodes)
and freed only when it finishes; NO queue (`queue_capacity = 0`), so
over-subscription is an error rather than a wait. This makes the
VM's FIFO service semantically identical to the Lean concurrency
model (`active decodes ≤ workers` at every instant): both report
`DECODER_OVERLOAD` on the same schedules. The 2 ms reaction budget
leaves headroom so the overload is the ONLY violation.
defge2021_physical
def ge2021_physical : HardwareSpec
The physical-budget architecture (Lean-side audits).
defge2021_logical
def ge2021_logical : HardwareSpec
The patch-granular GE2021 machine (the QEC→system lane's target).
theoremge2021_logical_fits_physical_budget
theorem ge2021_logical_fits_physical_budget :
FormalRV.System.RSA2048.computationZoneQubits
+ FormalRV.System.RSA2048.factoriesNeeded
* FormalRV.System.RSA2048.cczFactoryQubits
≤ FormalRV.System.RSA2048.physicalBudgetThe patch-granular layout's implied PHYSICAL cost fits the paper's
20 M budget: 6200 tiles × 1568 + 1093 factories × 2565 ≤ 20 000 000
(the residual is distillation/routing headroom).
theoremge2021_wellFormed
theorem ge2021_wellFormed :
(ge2021_physical.wellFormed && ge2021_logical.wellFormed) = truedefsurface_d3_stream
def surface_d3_stream : HardwareSpec
*Surface-code syndrome-streaming machine**: a 4×4 tile of d=3 surface
patches. Each patch is read out once per round as ONE `Measure` op on
its `syn` site, contributing 8 stabilizers × 8-bit soft data = 64 bits
to the syndrome stream; the classical link carries **4 KB/ms**
(`max_bits = 32768` per 1000 µs). Budget arithmetic: a round costs
16 × 64 = 1024 bits, so the link sustains at most
⌊32768 / 1024⌋ = 32 rounds per ms — a 25 µs cadence (40 rounds/ms =
40960 bits/ms) BREAKS the link; a 40 µs cadence (25 rounds/ms =
25600 bits/ms) fits.
definvariant_demo
def invariant_demo : HardwareSpec
*Invariant-examples machine** (`SystemInvariantExamples.demoArch`):
Data/Ancilla/Factory × 100, 1 µs cycle, 10 µs reaction, and the qianxu
CCZ-factory demand window (≤ 1 magic state per 12 000 µs).
defppm_pair
def ppm_pair : HardwareSpec
*PPM-pair machine** (`PPMContractInstances.ppm_pair_arch`):
Data/Ancilla × 100.
defftDemo
def ftDemo : HardwareSpec
*Fault-tolerant worked-instance machine** — the arch that
`Checkers/FaultTolerantSchedule.demoArch` AND its acknowledged mirror
`Invariants/InvariantFramework.demoArch` both define: 4 zones × 10
sites, 100 µs stabilizer cycle, 5 µm/µs transport limit. §6 pins both
mirrors to this single entry.
theoremblock_ok_on_adder_d3
theorem block_ok_on_adder_d3 :
checkScheduleOn adder_d3 (compileSurgeryGadgetToSysCalls surgery_ppm_A)
= trueThe sequential surgery block PASSES on the standard machine.
theoremblock_fails_on_zeroReaction
theorem block_fails_on_zeroReaction :
checkScheduleOn adder_d3_zeroReaction
(compileSurgeryGadgetToSysCalls surgery_ppm_A) = falseThe SAME block FAILS on the zero-reaction machine — the decoder
budget is live.
theoremparallel_fails_on_adder_d3
theorem parallel_fails_on_adder_d3 :
checkScheduleOn adder_d3 bad_parallel_adder_syscalls = falseThe parallel adder FAILS on the standard machine (CNOT cap 1)…
theoremparallel_ok_on_dualRail
theorem parallel_ok_on_dualRail :
checkScheduleOn adder_d3_dualRail bad_parallel_adder_syscalls = true…and the SAME schedule PASSES on the dual-rail machine (CNOT cap 2) —
the control-parallelism cap is live. Reconfiguring the catalog entry
changes which schedules are feasible, with no checker changes.
defsyndromeBurst
def syndromeBurst (rounds cadence : Nat) : List SysCall
A burst of patch readouts at the given cadence: one `Measure` per
`syn` site (16..31) per round, `rounds` rounds spaced `cadence` µs.
theoremsyndrome_flood_rejected
theorem syndrome_flood_rejected :
checkScheduleOn surface_d3_stream (syndromeBurst 40 25) = falseThe syndrome BIT accounting is live: 40 rounds × 16 patches × 64 bits
= 40960 bits inside one 1000 µs window EXCEEDS the 4 KB/ms link…
theoremsyndrome_paced_accepted
theorem syndrome_paced_accepted :
checkScheduleOn surface_d3_stream (syndromeBurst 25 40) = true…while 25 rounds/ms × 1024 bits = 25600 ≤ 32768 fits the same link —
and the very same flood is fine on a machine with no link contract.
theoremsyndrome_flood_ok_without_link_contract
theorem syndrome_flood_ok_without_link_contract :
checkScheduleOn { surface_d3_stream with syndromedefdecodesAt
def decodesAt (times : List Nat) : List SysCall
`n` decode calls of 1 ms each, at the given times (offset past a
prefix of n sequential 1 µs measurements on data sites — each decode
is causally fed, so I6.a is satisfied and the theorems below isolate
decoder OCCUPANCY).
theoremdecoder_paced_reuse_accepted
theorem decoder_paced_reuse_accepted :
checkScheduleOn adder_d3_strictDecoder
(decodesAt [0, 0, 1000, 1000, 2000, 2000]) = trueDecoder-occupancy semantics, positive: 6 one-millisecond decodes
through 2 workers succeed ONLY because each worker is freed when its
decode finishes (exactly 1000 µs after it began, half-open) and
immediately reused.
theoremdecoder_premature_reuse_rejected
theorem decoder_premature_reuse_rejected :
checkScheduleOn adder_d3_strictDecoder
(decodesAt [0, 0, 999]) = false…negative: reusing a worker 1 µs BEFORE its decode finishes makes 3
decodes simultaneously active on 2 workers — rejected. The decoder
is finite and its latency is real.
theoremdecode_after_measure_accepted
theorem decode_after_measure_accepted :
checkScheduleOn adder_d3
[ { kindMeasure [2,3) then decode [3,4): causal — ACCEPTED.
theoremdecode_before_measure_rejected
theorem decode_before_measure_rejected :
checkScheduleOn adder_d3
[ { kindThe decoder called at t = 2 while the measurement still runs until
t = 3 — the syndrome data does not exist yet: REJECTED, even though
every resource is free.
theoremsecond_magic_unprepared_rejected
theorem second_magic_unprepared_rejected :
checkScheduleOn adder_d3_magicScarce
[ { kindTWO magic consumptions against ONE prepared state: the second is
causally impossible — REJECTED on the scarce machine…
theoremsecond_magic_after_production_accepted
theorem second_magic_after_production_accepted :
checkScheduleOn
{ adder_d3_magicScarce with
magic_period_us…but ACCEPTED once a factory PREPARES one more state every 12 000 µs
and the second consumption waits for the batch to finish (t = 12 000):
prepare-before-consume, on the production curve.
theoremsecond_magic_during_production_rejected
theorem second_magic_during_production_rejected :
checkScheduleOn
{ adder_d3_magicScarce with
magic_period_us…and the same second consumption ONE µs before the batch finishes is
rejected: preparation must COMPLETE first.
theoremadder_d3_arch_eq
theorem adder_d3_arch_eq : adder_d3.toZonedArch = surgery_arch
theoremadder_d3_opCap_eq
theorem adder_d3_opCap_eq : adder_d3.toOpCap = adder_demo_opCap
theoremadder_d3_slotCap_eq
theorem adder_d3_slotCap_eq :
adder_d3.toSlotCap = generous_slot_capacity_modeltheoremadder_d3_ancilla_eq
theorem adder_d3_ancilla_eq :
adder_d3.toAncillaModel = demo_ancilla_modeltheoreminvariant_demo_arch_eq
theorem invariant_demo_arch_eq :
invariant_demo.toZonedArch
= FormalRV.System.SystemInvariantExamples.demoArchtheoremppm_pair_arch_eq
theorem ppm_pair_arch_eq :
ppm_pair.toZonedArch
= FormalRV.System.LatticeSurgeryPPMContract.ppm_pair_archtheoremftDemo_arch_eq_checker
theorem ftDemo_arch_eq_checker :
ftDemo.toZonedArch = FormalRV.System.FTSchedule.demoArchThe two mirrored worked-instance archs are BOTH this catalog entry —
the duplication is now formally pinned to one source.
theoremftDemo_arch_eq_framework
theorem ftDemo_arch_eq_framework :
ftDemo.toZonedArch = FormalRV.System.InvariantFramework.demoArchtheoremcatalog_wellFormed
theorem catalog_wellFormed :
(adder_d3.wellFormed && adder_d3_dualRail.wellFormed
&& adder_d3_zeroReaction.wellFormed && invariant_demo.wellFormed
&& ppm_pair.wellFormed && ftDemo.wellFormed) = trueCatalog entries are well-formed configurations.
FormalRV.System.Params.HardwareParams
FormalRV/System/Params/HardwareParams.lean
FormalRV.System.HardwareParams — the ONE canonical hardware-parameter record that reconciles the
four hardware records the two scheduling subsystems grew independently:
`DeviceSchedule.Device` (DeviceOp-schedule view: totalResources, nDecoders,
reactionTime, codeCycleUs, d)
`ScheduleInvariantsExplicit.ZonedArch` (SysCall-checker view: total_sites, t_cycle_us,
v_max_um_per_us, t_react_us)
`FaultTolerantSchedule.FTSchedule` (FT bundle: arch + code_distance, tau_s, t_react_us)
`HardwareSensitivity.HW` (sensitivity view: Q, nDec, tReact, d, …)
Rather than RENAME/move fields (which would ripple into dozens of literals + `native_decide`
proofs), this file introduces a canonical superset `MachineParams` and PROJECTION adapters. The
`reaction_*_eq` lemmas are definitional glue (`rfl`): they NAME which field of each record the
adapters read as the decoder-reaction budget — they do not certify any pre-existing agreement
between the records. This is the single grep-able anchor for "where decoder reaction lives".
structureMachineParams
structure MachineParams
The canonical hardware-parameter record: the union of the four views' physical quantities.
defMachineParams.ofDevice
def MachineParams.ofDevice (dev : Device) : MachineParams
Projection from the DeviceOp-schedule `Device` (the most complete view).
defMachineParams.ofZonedArch
def MachineParams.ofZonedArch (a : ZonedArch) : MachineParams
Projection from the SysCall-checker `ZonedArch` (no decoder count or distance → documented 0).
defMachineParams.ofHW
def MachineParams.ofHW (h : HW) : MachineParams
Projection from the sensitivity `HW` record (no explicit cycle time → documented 0).
theoremreaction_device_eq
theorem reaction_device_eq (dev : Device) :
(MachineParams.ofDevice dev).tReactUs = dev.reactionTimetheoremreaction_arch_eq
theorem reaction_arch_eq (a : ZonedArch) :
(MachineParams.ofZonedArch a).tReactUs = a.t_react_ustheoremreaction_hw_eq
theorem reaction_hw_eq (h : HW) :
(MachineParams.ofHW h).tReactUs = h.tReactdefftReactionConsistent
def ftReactionConsistent (f : FTSchedule) : Bool
The FT bundle carries `t_react_us` separately from its `arch.t_react_us`; this predicate
documents the intended invariant that the two agree (rather than forcing a struct change).
theoremreaction_ft_eq
theorem reaction_ft_eq (f : FTSchedule) (h : ftReactionConsistent f = true) :
f.t_react_us = (MachineParams.ofZonedArch f.arch).tReactUsThe reaction budget the FT bundle uses equals the one in its architecture, via the canonical
projection — provided the bundle is consistent.
defge2021Device
def ge2021Device : Device
The GE2021 device (`DeviceSchedule` view) used to anchor the reaction budget at 10 µs.
theoremge2021_reaction_canonical
theorem ge2021_reaction_canonical :
(MachineParams.ofHW ge2021).tReactUs = 10
∧ (MachineParams.ofDevice ge2021Device).tReactUs = 10Both GE2021 instances (`HardwareSensitivity.ge2021` and `ge2021Device` above) carry a 10 µs
reaction budget — definitional (`rfl`), since both records store the literal 10.
FormalRV.System.Params.RSA2048
FormalRV/System/Params/RSA2048.lean
FormalRV.System.Params.RSA2048 — the canonical RSA-2048 / Gidney–Ekerå 2021
workload constants, in ONE place.
Before this module the same numerals were re-typed in seven `System/` files
(and drifted between doc-comments); every System file that needs a GE2021
number should reference these definitions instead of re-typing the literal.
All are plain `Nat` definitions, so `decide` / `native_decide` proofs unfold
them for free.
Sources: Gidney–Ekerå 2021 (2.7·10⁹ Toffolis, 6200 logical patches, 20 M
physical qubits, ~8 h) and Cain–Xu 2026 App. C (CCZ factory: 2565 qubits,
12 000 µs window). The magic budget 2 622 824 448 is the PAPER cost-model
windowed CCZ count (`= WindowedCostModel.toffoliCount 2048 3072 11`). The
count of the *actually-composed* circuit (`WindowedComposed.modExp`) is
2 578 993 152 (`WindowedComposedCost.rsa2048_head_to_head`); the paper figure
is a PROVEN UPPER BOUND on it (+1.67 % runway-folding + lookup-rounding) — see
`System.Compose.VerifiedWorkloadBridge` (`verifiedToffoli_le_magicBudget`).
(`Shor.Resource.ModExpToffoliCount` is the *un-windowed* 16n³ schoolbook bound,
a different, ~51× larger circuit — NOT this number.)
abbrevtoffoliReported
abbrev toffoliReported : Nat
GE2021's reported Toffoli count for RSA-2048 (2.7·10⁹).
abbrevmagicBudget
abbrev magicBudget : Nat
The paper cost-model CCZ/magic-state budget for the windowed RSA-2048 circuit
(`= WindowedCostModel.toffoliCount 2048 3072 11`). It is a PROVEN UPPER BOUND on the
actually-composed circuit's count `2 578 993 152` (`= EGate.toffoli WindowedComposed.modExp`;
see `System.Compose.VerifiedWorkloadBridge.verifiedToffoli_le_magicBudget`), so any
provisioning sized for `magicBudget` covers the verified circuit.
abbrevpatches
abbrev patches : Nat
Logical surface-code patches in the GE2021 layout.
abbrevdecodeLatencyCycles
abbrev decodeLatencyCycles : Nat
Decoder latency budget, in code cycles.
abbrevdecodeLanesRequired
abbrev decodeLanesRequired : Nat
Decode lanes required for backlog-free decoding:
`patches · decodeLatencyCycles` (see `Decoder/DecoderBacklogModel`).
abbrevcczFactoryQubits
abbrev cczFactoryQubits : Nat
CCZ factory footprint, physical qubits (Cain–Xu 2026 App. C).
abbrevcczWindowUs
abbrev cczWindowUs : Nat
CCZ factory production window, µs (one magic state per window).
abbrevfactoriesNeeded
abbrev factoriesNeeded : Nat
CCZ factories needed to keep RSA-2048 reaction-limited
(see `Magic/MagicScheduleComplete`, `Audit/GidneyEkera2021/SystemZones`).
abbrevdistance
abbrev distance : Nat
Surface-code distance of the computation patches.
abbrevtileQubits
abbrev tileQubits : Nat
Physical qubits per logical tile: `2(d+1)²` at d = 27 (the ×2 is the
routing share baked into the GE2021 tile accounting).
abbrevphysicalBudget
abbrev physicalBudget : Nat
The reported total physical-qubit budget (the title's 20 M).
abbrevcycleUs
abbrev cycleUs : Nat
Surface-code cycle time, µs.
abbrevreactionUs
abbrev reactionUs : Nat
Reaction-time budget, µs (= `decodeLatencyCycles · cycleUs`).
abbrevcomputationZoneQubits
abbrev computationZoneQubits : Nat
Computation-zone physical qubits: every patch as a d = 27 tile.
abbrevsyndromeBitsPerPatchRound
abbrev syndromeBitsPerPatchRound : Nat
Syndrome bits one patch readout injects per round: `d² − 1` hard
stabilizer bits at d = 27 (rotated surface code).
theoremdecodeLanesRequired_value
theorem decodeLanesRequired_value : decodeLanesRequired = 62_000
theoremcomputationZoneQubits_value
theorem computationZoneQubits_value : computationZoneQubits = 9_721_600
theoremsyndromeBitsPerPatchRound_value
theorem syndromeBitsPerPatchRound_value :
syndromeBitsPerPatchRound = 728FormalRV.System.Params.ZoneBudget
FormalRV/System/Params/ZoneBudget.lean
FormalRV.System.ZoneBudget — let the USER set their architecture's per-zone qubit
counts, and build the zoned architecture from them. Hardware-agnostic; the
neutral-atom (qianxu) layout is one instance.
The user supplies a list of (zone name, qubit count); `toArch` lays the zones out
contiguously into a `ZonedArch` whose `total_sites` is the SUM of the counts, and
the capacity invariant then checks every operation lands inside a finite zone.
So "how many qubits in each zone" is a first-class, user-settable input.
qianxu's total (ED Table III): N_m (memory) + N_p (processor) + 3·N_f (factories)
+ N_𝒜 (operation-zone ancilla, 894 for lp_20^{3,7}) + N_res (reservoir/reloading).
We fix the KNOWN counts (N_𝒜 = 894, one factory ≈ 2565) and leave N_m, N_p, N_res
as user parameters — N_res in particular is UNSPECIFIED in the paper (a real gap).
No `sorry`, no `axiom`.
structureZoneBudget
structure ZoneBudget
A per-zone qubit budget: named zones with their physical-qubit counts, plus the
cycle time and transport speed. Hardware-agnostic (the user names the zones).
defZoneBudget.total
def ZoneBudget.total (b : ZoneBudget) : Nat
Total physical qubits = sum of the per-zone counts.
deflayoutZones
def layoutZones : List (String × Nat) → Nat → List ArchZone
| [], _ => []
| (name, cnt) :: rest, off =>
{ nameLay named zones out contiguously from a running offset into `ArchZone`s.
defZoneBudget.toArch
def ZoneBudget.toArch (b : ZoneBudget) : ZonedArch
Build the `ZonedArch` from the user's zone budget.
theoremtoArch_total
theorem toArch_total (b : ZoneBudget) : b.toArch.total_sites = b.total
The built architecture's total qubit count is exactly the user's zone sum.
theoremlayout_zone_capacity
theorem layout_zone_capacity (name : String) (cnt : Nat) (rest : List (String × Nat)) (off : Nat) :
((layoutZones ((name, cnt) :: rest) off).head?.map ArchZone.capacity) = some cntThe FIRST zone's capacity in the built layout is exactly its user-set count. (Only the head
of the list is inspected; later zones follow by applying this at the recursive tail
`layoutZones rest (off + cnt)` — no all-zones statement is proven here.)
defqianxuBudget
def qianxuBudget (N_m N_p N_res tCycle vMax : Nat) : ZoneBudget
qianxu (lp_20^{3,7}) zone budget: KNOWN counts factory ≈ 2565 (App C) and
operation-zone ancilla N_𝒜 = 894 (ED Table III); memory `N_m`, processor `N_p`,
and reservoir `N_res` are user parameters (`N_res` is UNSPECIFIED in the paper).
theoremqianxu_total
theorem qianxu_total (N_m N_p N_res tCycle vMax : Nat) :
(qianxuBudget N_m N_p N_res tCycle vMax).total = N_m + N_p + 2565 + 894 + N_resqianxu total = N_m + N_p + 2565 + 894 + N_res — the sum-over-zones of ED Table
III, with the factory and operation-ancilla counts fixed to the paper's values.
theoremqianxu_10k_instance
theorem qianxu_10k_instance :
(qianxuBudget 4000 2541 0 1 1).total = 10_000A representative ~10,000-qubit instance (memory 4000, processor 2541,
reservoir 0): total = 10,000, matching the paper's headline. (The exact
N_m/N_p/N_res split is the user's to set / the paper's ED Table III to pin;
N_res is the paper's unspecified zone.)
theoremqianxu_10k_arch_total
theorem qianxu_10k_arch_total :
(qianxuBudget 4000 2541 0 1 1).toArch.total_sites = 10_000The built qianxu architecture reports the 10,000-qubit total.
theoremtotal_mono_memory
theorem total_mono_memory (N_m N_m' N_p N_res tC vM : Nat) (h : N_m ≤ N_m') :
(qianxuBudget N_m N_p N_res tC vM).total ≤ (qianxuBudget N_m' N_p N_res tC vM).totalThe total is monotone (non-strict, `≤`) in the MEMORY budget `N_m`. Only this one zone is
covered; the analogous statements for `N_p`/`N_res` would be proved the same way but are not
stated here.