System 1020 declarations in 35 modules
FormalRV.System.AdderSystem
FormalRV/System/AdderSystem.lean
FormalRV.Framework.AdderSystem — first concrete
system-level review instance.
## Why an adder (not full Shor)
Starting from a small adder-level construction is a deliberate
choice: full FT Shor at RSA-2048 scale is beyond what we can
construct as a literal `List SysCall` and decide on with
`native_decide`. An adder skeleton is large enough to be
structurally interesting (many Gate2q / Measure / Decode /
PauliFrameUpdate calls) but small enough that the entire strict
system-checker bundle closes by `native_decide`.
## What this tick demonstrates
The framework's gap-reporting workflow:
(1) **Concrete construction.** An adder-level `List SysCall`
composed of existing topology-compiled PPM gadgets.
(2) **Strict system certificate.** The schedule passes
`all_invariants_strict_with_slot_capacity_and_freshness_ok`
— the strongest current bundle.
(3) **Derived resources.** Wallclock, total SysCall count,
per-kind counts — all computed by `foldl` / `filter` over
the actual schedule.
(4) **Claim comparison.** An optimistic paper-style claim
object whose claimed wallclock is FORMALLY below the
verified value.
(5) **Capacity lower bound.** Under the same
operation-capacity assumptions used to certify the
schedule, ANY schedule with the same Gate2q count is
bounded below by `ceildiv(num_gate2q, max_parallel) ·
gate2q_us`; the optimistic claim is below this bound too.
## 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. Arithmetic correctness lives at the
Gate IR level (`BQAlgo/RippleCarryAdder.lean`,
`Framework/CuccaroParametric.lean`). Connecting Gate IR
to SysCall emission is a separate piece of work.
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` or `rfl`.
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 = `foldl Nat.max sc.end_us 0`.
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_is_derived
theorem adder_n1_wallclock_is_derived :
adder_n1_wallclock_us
= adder_n1_syscalls.foldl (fun acc sc => Nat.max acc sc.end_us) 0*Anti-spreadsheet (rfl)**: wallclock is the foldl.
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 is
formally below the Gate2q capacity lower bound under the
same `OperationCapacityModel` used to certify the
schedule.
Interpretation: even abstracting away decoder budget,
ancilla lifecycle, and timing nuance, NO schedule emitting
18 Gate2qs with `max_gate2q_active = 1` can fit in 1 µs.
The optimistic claim contradicts its own capacity
assumptions.
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.Architecture
FormalRV/System/Architecture.lean
FormalRV.Framework.Architecture — cross-platform architecture
abstraction for fault-tolerant quantum computers.
Designed (2026-05-22, per John's directive) to apply 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; the
same `verifies_iff` machinery produces a hardware target for it.
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. Note: per-channel quantities (bandwidth,
latency, fidelity) replace the previous scalar `HardwareParams`
fields like `t_layer_us` and `reload_per_ms`.
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*Semantic correctness of a schedule.** Every SysCall has
its structural precondition met in the schedule's context.
A schedule that fails this check is not just inefficient —
it does not represent a valid quantum operation on any
hardware. Resource verification (capacity, latency,
bandwidth, fidelity) on a semantically-incorrect schedule 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 a SQIR-side proof
via `SemanticSqirBridge.lean`.
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 — see `notes/zac-comparison.md`.
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.CodedLayout
FormalRV/System/CodedLayout.lean
FormalRV.Framework.CodedLayout — code-block-aware logical
layout for QEC codes.
Per John's directive (2026-05-22): the framework must support
declaring that a computation uses a specific QEC code (e.g.
`[[144, 18, 12]]`) and reference logical qubits by their
local index within that code block.
Compared to the existing `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`.
Concrete example (the LPCodedAdderDemo): an adder using
logical qubits 3, 15, 17 in an `[[144, 18, 12]]` code block.
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 / ancilla
requests) return `[]`.
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.CompressedRepeatSoundness
FormalRV/System/CompressedRepeatSoundness.lean
FormalRV.Framework.CompressedRepeatSoundness — foundational
shift / repetition lemmas toward parametric symbolic-repeat
soundness.
## Goal
Push toward
symbolic_rep_strict_ok models body n = true
→
all_invariants_strict_with_slot_capacity_and_freshness_ok
... (rep n (atom body)).expand ... = true
by establishing the foundational shift / repetition lemmas
each strict-bundle conjunct needs.
## What this tick closes
(§1) Pure-`rfl` shift lemmas: `kind`, `begin_us`,
`end_us`, `syscall_acts_on`,
`syscall_factory_claims` are all `rfl`-preserved
(or shifted in the obvious way).
(§2-§4) Shift invariance of the per-call invariants
that depend only on `kind` and `end_us - begin_us`:
`capacity_in_arch_ok`, `feedback_latency_ok`,
`decoder_react_ok`.
(§5) Ancilla-freshness shift invariance — the freshness
state machine reads only `sc.kind`. Closed
parametrically.
(§6) No-magic-count preservation under shift.
(§7) `kindIs*` predicates are shift-invariant.
(§8) Concrete repeat examples: `n=10` cross-check via
expansion + `native_decide`; `n=1_000_000` symbolic
check via the previous tick's
`symbolic_rep_strict_ok` (NO expansion).
## What this tick does NOT close
The PARAMETRIC theorem
`symbolic_rep_strict_ok_implies_expanded_strict_ok` for
arbitrary `n` is NOT proven this tick. The remaining
obligation is split into two genuinely harder pieces:
(A) **Sequential composition** on `seqSchedules xs ys`
for `exclusivity_ok`, `capacity_per_cycle_ok`,
`operation_capacity_ok`, `slot_capacity_ok`,
`factory_exclusivity_ok`. These all rely on
argument-window disjointness (a SysCall in `xs`
ends at `≤ scheduleWallclockUs xs` and a SysCall in
the shifted `ys` begins at `≥ scheduleWallclockUs xs`,
so the half-open intervals are disjoint and pairwise
checks pass). Each lemma is a small bounded
argument but the proof is long because the
pairwise checkers use `List.range n .all (fun i =>
List.range n .all ...)` over indices.
(B) **Feedback-after-decode** under
`seqSchedules`. The inner `.any` references the
whole combined list, so the shift-invariance proof
requires a helper lemma that the inner condition is
≤-preserved under uniform `+dt`.
(C) **Ancilla-freshness state-monotonicity** across the
boundary. Each copy's first `RequestFreshAncilla`
starts from a state in which the previous copy left
the ancilla sites `Dirty`; the body was validated
from `Free`. The `next free site` rule treats
`Free` and `Dirty` identically, so the trajectory
is the same — but formalising this requires a
state-equivalence lemma on `runFreshness`.
Each obligation is well-scoped; the parametric theorem
follows by conjunction once all three pieces close.
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 = 0theoremadder_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**: `n=1_000_000` symbolic check
via `symbolic_rep_strict_ok`. The check is `O(|body|)`,
independent of `n` — Lean does NOT materialise 1,000,000
SysCall copies.
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`.
defscheduleWithinWallclock
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).
theoremadder_n1_scheduleWithinWallclock
theorem adder_n1_scheduleWithinWallclock :
scheduleWithinWallclock adder_n1_syscalls = truetheoremscheduleWithinWallclock_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 = falsedefadder_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 = truedefdecode_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_via_helper
theorem feedback_after_decode_ok_via_helper (sched : List SysCall) :
feedback_after_decode_ok sched
= sched.all fun sc => match sc.kind with
| .PauliFrameUpdate cid =>
sched.any (decode_matches_feedback cid sc.begin_us)
| _ => truetheoremfeedback_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`.
theoremrep_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`.
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.**
theoremadder_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 = falsedeflifecycleEquivalent
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)theoremfindFreeOrDirtyInZone_state_equivalent
theorem findFreeOrDirtyInZone_state_equivalent
{s1 s2 : List (Nat × SiteLifecycle)}
(h : state_equivalent s1 s2) (z : AncillaZoneSpec) :
findFreeOrDirtyInZone s1 z = findFreeOrDirtyInZone s2 ztheoremfreshnessStep_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 = truetheoremadder_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) still passes the ancilla-freshness check.
Closed by `native_decide` on the expansion (the
parametric chain would close this for arbitrary `n`
once the normalization invariants are added).
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 = falsetheoremsymbolic_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 = truetheoremshiftSchedule_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 = truetheoremcountActiveKindAt_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 = truetheoremcapacity_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 = truetheoremsymbolic_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.
`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.
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.ConcreteMachineFeasibility
FormalRV/System/ConcreteMachineFeasibility.lean
FormalRV.System.ConcreteMachineFeasibility — "can THIS concrete machine factor
RSA-2048?" Feasibility against a FIXED finite qubit budget, plus a pluggable
hardware CONNECTIVITY (coupling-map) constraint.
The point: a resource estimate is only meaningful relative to a concrete machine.
Given a machine with a bounded number of physical qubits (and, optionally, a
connectivity constraint), the framework decides whether the algorithm FITS — and
rejects it when it does not. For RSA-2048 the data block alone is irreducible:
~6200 logical qubits, each a distance-`d` surface tile of `2(d+1)²` physical
qubits, all live simultaneously (they hold the quantum state — you cannot
time-share them). So a 100 000-qubit machine CANNOT factor RSA-2048 at d=27,
and the framework proves it.
Hardware-neutral core; the connectivity limit is a hardware-specific pluggable
`SpaceTimeInvariant` (superconducting nearest-neighbour, ion all-to-all,
neutral-atom reconfigurable each supply their own `couples`).
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 (Ekerå–Håstad windowed, ≈ 6200).
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.CostModelWeightDemo
FormalRV/System/CostModelWeightDemo.lean
FormalRV.System.CostModelWeightDemo — wiring the purpose-tagged ancilla budget
to REAL code data.
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`.
example(example)
example :
((qldpcModel 0).ancilla code422Q w0 (rowWeight (code422Logical.selectZ [0])) 1).surgery = 2Wiring: the qLDPC SURGERY ancilla for measuring Z̄₀ equals the operator's
real weight (2), fed in as `op_weight = rowWeight (selectZ [0])` — 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.DecodeLatencySensitivity
FormalRV/System/DecodeLatencySensitivity.lean
FormalRV.System.DecodeLatencySensitivity — make the DECODE LATENCY a first-class
USER-SPECIFIED input that FLOWS INTO the verified runtime (not a buried constant),
and show it couples to the subtler system scheduling (decoder provisioning).
The audit noted the decode latency was used in a CHECK (`decoderInv` / the
SystemCtx field `t_react_us`) and in a FIXED def (`reactionTime_tenthsUs := 100`),
but it never entered the runtime FORMULA (which charged `tauToff = d`, the code
distance — independent of the decoder). Reaction-limited execution (GE2021)
charges the DECODE LATENCY per logical Toffoli, so the latency directly sets the
runtime. We make this a verified, tunable cost model:
• a `reactionLimitedModel decodeLatency` whose `tauToff` IS the decode latency
(in cycles) — so the verified `estimateWith` time = n_toff · decodeLatency ·
cycle, a function of the user's decode latency;
• MONOTONICITY: a slower decoder ⇒ a strictly 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 (reaction-limited = d-cycle ceiling);
• the COUPLING (subtle scheduling): the SAME decode-latency input also scales
the decoder LANE requirement (patches · decodeLatency), 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 * L*The two effects together, parametric.** 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` — both LINEAR in the user's decode-latency input.
FormalRV.System.DecoderBacklogModel
FormalRV/System/DecoderBacklogModel.lean
FormalRV.System.DecoderBacklogModel — a FULL PARAMETRIC model of the decoder
throughput / backlog gap (audit GAP 1, the most dangerous and user-flagged).
The earlier `ResourceAuditGaps.decoderThroughputInv` only stated a one-shot
`load ≤ lanes` check. This module models the QUEUE DYNAMICS over time and proves
the dichotomy that makes the gap real:
• 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.
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.DependencyGraph
FormalRV/System/DependencyGraph.lean
FormalRV.System.DependencyGraph — a first-class CAUSAL-DEPENDENCY graph for
parallel schedules: the (B) half of "max parallelism subject to invariants".
John's insight (2026-06-02): the system invariants are about two things —
(A) RESOURCE conflict-freedom and (B) CAUSAL dependencies — and (B) is just as
essential. (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 — crucially — 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.
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.DeviceSchedule
FormalRV/System/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 + a representative Shor-fragment demo + the resource-number connection
(`DeviceScheduleCapstone`) 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.
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.FTFramework
FormalRV/System/FTFramework.lean
FormalRV.System.FTFramework — the SINGLE coherent 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 all four 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 well-formed naive system 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, with
the horizon / floor inputs for the resource bracket.
defFTSystem.wellFormed
def FTSystem.wellFormed (S : FTSystem) : Bool
Well-formedness (for finite schedules): the schedule is valid AND the device mirrors the
canonical hardware record.
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)
(_hcoh : MachineParams.ofDevice S.dev = S.hw) :
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 whose hardware record mirrors the 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.FaultTolerantSchedule
FormalRV/System/FaultTolerantSchedule.lean
FormalRV.Framework.FTSchedule — SYSTEM-LEVEL FAULT-TOLERANT SCHEDULING.
The four hardware concerns are syscalls — RequestMagicState (T-factory),
RequestFreshAncilla (ancilla), TransitQubit (routing), DecodeSyndrome
(classical decoding) — and the four decidable invariants (capacity,
exclusivity, latency/speed, throughput) guarantee they are schedulable.
`ft_ok` bundles those with 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 `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.
**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.
## Honest scope note on the latency rung
The chosen bundle is exactly `ScheduleInv.all_invariants_ok`, whose latency
conjunct is `latency_speed_ok` = feedback-latency ∧ speed-limit. It does
NOT include `decoder_react_ok` (a separate decidable checker in
`ScheduleInvariantsExplicit`). Hence a too-slow `DecodeSyndrome` alone does
NOT trip `ft_ok`; the latency violations that DO trip it are a too-slow
feedback or a transit that outruns the speed limit. The negative test
`demoFT_slowTransit` below trips on the speed limit (the routing rung the
bundle actually enforces).
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 four system invariants (capacity = ancilla,
exclusivity, latency/speed = routing, throughput = T-factory) AND the
real-time DECODER reaction-time bound (each `DecodeSyndrome` completes within
`t_react_us` — the qianxu within-cycle decoding claim; `all_invariants_ok`
alone does NOT enforce this, so we add `decoder_react_ok` explicitly) 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.
defcountKind
def countKind (p : SysCallKind → Bool) (s : List SysCall) : Nat
Count syscalls whose kind satisfies the predicate `p`.
defmagicStateCount
def magicStateCount (s : List SysCall) : Nat
Number of magic-state requests (T-factory consumption).
defancillaCount
def ancillaCount (s : List SysCall) : Nat
Number of fresh-ancilla requests.
defdecodeRounds
def decodeRounds (s : List SysCall) : Nat
Number of decoder rounds.
defroutingMoves
def routingMoves (s : List SysCall) : Nat
Number of routing moves (qubit transits).
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: the real-time decoder reaction budget `t_react_us := 2` is
below the `DecodeSyndrome` latency (25 − 20 = 5), so `decoder_react_ok` fails
⇒ `ft_ok = false`. This is the classical-decoding rung of fault-tolerance
(the qianxu within-cycle decoding requirement), now caught.
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.HardwareErrorParams
FormalRV/System/HardwareErrorParams.lean
FormalRV.Framework.HardwareErrorParams — implementer-side
error-rate inputs.
These numbers are the implementer's hardware-and-compilation
characterization, expressed in parts-per-million (ppm) for
decidability. Each field is what the L3 → L2 / L4 → L3 inter-
layer contracts produce when given a specific QEC code, gate
error rate, and PPM gadget set. The implementer JUSTIFIES
each number by citing the contract and the underlying
paper/derivation; the framework just consumes the numbers and
composes them via union bound.
## Why these fields specifically
The framework's coarse PPM compilation produces SysCalls of
four kinds: PPM-like (Pauli-product measurement),
magicReq (magic-state injection: T or CCZ), route (atom
transport), and feedback (classical decoder reaction). Each
contributes a different error. The fields below capture the
per-syscall logical-error contribution in ppm.
## Conservatism
Each field is a **maximum** — the implementer should report
the upper bound on the error contribution from the worst-case
instance of that syscall kind. The framework then sums via
union bound; the result is a conservative over-estimate of
the total logical error budget.
No Mathlib dependency. All-Nat for `decide`.
structureHardwareErrorParams
structure HardwareErrorParams
The per-SysCall error-rate inputs the implementer supplies.
Each field has units of parts-per-million (ppm) of the final
output state's logical-error contribution. E.g.,
`ppm_op_error_ppm = 100` means each PPM operation contributes
at most 100 ppm = 1e-4 to the union-bound error budget.
defqianxu_class
def qianxu_class : HardwareErrorParams
A "qianxu-class" default: gate error 1e-3, T-state infidelity
1e-6 from 15-to-1, CCZ infidelity 1e-6 from 8T-to-CCZ, transit
idling ~10 ppm per route. These are illustrative defaults
only; real submissions must cite specific contracts.
FormalRV.System.HardwareParams
FormalRV/System/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, and
CERTIFIES — by `rfl` — that the decoder-reaction budget in all four records is literally the same
quantity (`tReactUs = Device.reactionTime = ZonedArch.t_react_us = HW.tReact = FTSchedule via its
arch`). 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 = 10The canonical projection agrees with `HardwareSensitivity`'s GE2021 instance and the
`DeviceSchedule` GE2021 device on the reaction budget (both 10 µs).
FormalRV.System.HardwareSensitivity
FormalRV/System/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.
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⁹). 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.
theoremsensitivity_complete
theorem sensitivity_complete (h : HW) (K depth : Nat) : 0 ≤ h.timeLB K depth
*Completeness.** Every listed hardware parameter has a proven sensitivity theorem above:
decoding speed (`decoderFloor_mono_tReact`, `depthFloor_mono_tReact`), architecture size
(`magicFloor_anti_Q`), routing latency + measurement time (`parFloor_mono_opTime`,
`depthFloor_mono_tMeas`), max parallelism (`parFloor_anti_maxPar`), decoder parallelism
(`decoderFloor_anti_nDec`), code distance (`physQubits_mono_d`), and factory cost
(`magicFloor_mono_prod`, `magicFloor_mono_fq`). None is dropped from the bound.
FormalRV.System.InvariantFramework
FormalRV/System/InvariantFramework.lean
FormalRV.Framework.InvariantFramework — EXTENSIBLE SPACE-TIME INVARIANT
FRAMEWORK.
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 (mirror of `FTSchedule.demoArch`).
defdemoDist
def demoDist : Nat → Nat
Route distance function: every channel covers 30 µm (mirror of
`FTSchedule.demoDist`).
defdemoSched
def demoSched : List SysCall
Worked-instance schedule (mirror 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.LayeredArtifactInterface
FormalRV/System/LayeredArtifactInterface.lean
FormalRV.Framework.LayeredArtifactInterface — shared
multi-layer artifact and certificate interface.
## Strategic role
The framework should support both:
(1) **Lean-generated** circuits / schedules / certificates.
(2) **Python / Qiskit / third-party-generated** circuits /
schedules / certificates.
Both target the SAME interfaces. Lean is the trusted
verifier; external tools may generate artifacts, but their
output must be re-checked by Lean.
## Layers covered
L1 logical Shor, modular exp, full adder
L2 gateIR Cuccaro / Gidney adder, lookups
L3 cliffordT / ppm Toffoli, CCZ teleport, PPM
L3' surgery lattice-surgery gadget IR
L4 syscall SysCall schedule
L4' compressedSchedule hierarchical schedule (TBD)
Each artifact carries:
a layer tag,
a metadata block (name, description),
a payload of the layer's concrete IR type,
(optionally) a verified certificate proving system-level
invariants on the lowered SysCall stream.
## What this tick delivers
`ArtifactLayer` + `ArtifactMetadata`.
`GateArtifact`, `SurgeryArtifact`,
`SysCallScheduleArtifact` — layer-specific payloads.
`SystemModels` — the system-side parameter bundle.
`VerifiedSysCallSchedule` — proof-carrying certificate
with `wallclock_derived` and `strict_ok` fields.
`LayerCompiler α β` — a uniform compiler interface;
instantiated by wrapping existing compilers.
`verified_syscall_schedule_of_strict_ok` — generic
checker theorem: anything that passes the strict bundle
yields a `VerifiedSysCallSchedule`.
Lean-generated example: `adder_n1_syscall_artifact` +
`adder_n1_artifact_verified` (reuses the existing
`adder_n1_strict_system_ok`, no re-proof).
`ExternalScheduleCertificate` — the Lean-side mock of
the format external tools must produce.
Checker functions on external certs:
`external_wallclock_matches`,
`external_syscall_count_matches`,
`external_gate2q_count_matches`,
`external_schedule_strict_ok` (bundle of all three +
strict-system invariants).
`python_generated_adder_example` (good) →
`python_generated_adder_example_checked = true`.
`python_bad_wallclock_example` (bad) →
`python_bad_wallclock_example_rejected = false`.
`CompressedSchedule` placeholder inductive — type only,
no eval semantics yet.
No new system-layer checks. No JSON parsing. No `sorry`,
no custom `axiom`.
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 = falseinductiveCompressedSchedule
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`.
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.
theoremresource_atom_sound
theorem resource_atom_sound (xs : List SysCall) :
(CompressedSchedule.atom xs).resource = resourceOfSysCalls xs*Soundness for atom.** The symbolic resource of
`atom xs` is `resourceOfSysCalls xs`.
theoremresource_wallclock_sound_atom
theorem resource_wallclock_sound_atom (xs : List SysCall) :
(CompressedSchedule.atom xs).resource.wallclock_us
= scheduleWallclockUs (CompressedSchedule.atom xs).expandWallclock soundness for `atom`.
theoremresource_syscall_count_sound_atom
theorem resource_syscall_count_sound_atom (xs : List SysCall) :
(CompressedSchedule.atom xs).resource.syscall_count
= (CompressedSchedule.atom xs).expand.lengthSysCall-count soundness for `atom`.
theoremresource_gate2q_count_sound_atom
theorem resource_gate2q_count_sound_atom (xs : List SysCall) :
(CompressedSchedule.atom xs).resource.gate2q_count
= ((CompressedSchedule.atom xs).expand.filter
(fun sc => kindIsGate2q sc.kind)).lengthGate2q-count soundness for `atom`.
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. For this tick, `reps` does
NOT enter the check — the sufficient condition is on the
body alone (which is the whole point of the scalability
fix).
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 * body.lengththeoremrepeated_schedule_resource_gate2q
theorem repeated_schedule_resource_gate2q
(body : List SysCall) (n : Nat) :
(CompressedSchedule.rep n (CompressedSchedule.atom body)).resource.gate2q_count
= n * (body.filter (fun sc => kindIsGate2q sc.kind)).lengththeoremsymbolic_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.
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.MagicScheduleComplete
FormalRV/System/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 (the circuit waits on
magic), and the device qubit budget decomposes as data + factory + routing.
Concrete numbers use the paper-cited `ccz_spec_qianxu`; the model is parametric in the
`MagicStateSpec`. No hallucinated factory numbers.
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 every gate waits exactly until
its magic is ready, so no gate consumes magic that does not exist yet.
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, the runtime IS
the magic pipeline — the circuit is bottlenecked on, and waits for, magic.
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.
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: no gate fires before its magic is produced and routed.
(2) **Magic-limited runtime** — at a single factory the magic pipeline dwarfs the logical
depth, so the runtime is the magic pipeline (the circuit waits on magic); this is why
`1093` parallel factories are required.
(3) **Qubit budget** — the device decomposes as data (`9 633 792`) + factory (`2 803 545`)
+ routing, all accounted; the magic share is derived, not assumed.
FormalRV.System.MagicStateReadiness
FormalRV/System/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.
## Motivation (per John's directive)
The `Architecture` model already declares `MagicStateSpec` (`production_us` latency,
`factory_qubits` footprint, fidelity) and the `RequestMagicState` / `TransitQubit` SysCalls and
`MagicSupply` channels — but `MagicStateSpec` was never bound to scheduling, and there was NO
invariant forcing a magic-CONSUMING operation to come AFTER the magic is produced and routed.
Without that, a circuit could "use" a magic state that does not physically exist yet.
This file binds them:
A magic state must be 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` / `deliveryLatency`: a consumer that fires before the delivery completes is
REJECTED — 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`: from the circuit's magic budget + a per-factory
throughput, the supply time and the NUMBER of factories follow — and hence the factory
qubit footprint, which is the magic share of the device's physical qubits.
Concrete numbers use the paper-cited `ccz_spec_qianxu` (`Architecture.lean`); the model is
parametric in the `MagicStateSpec`, so a Gidney–Ekerå-specific factory spec plugs in unchanged
once its cited values are available. No hallucinated factory numbers.
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 take `2 622 824 448 · 12000 µs ≈ 1.0×10⁹ s` — far beyond
any runtime budget, so the circuit would WAIT on magic. Hence parallelism is mandatory.
FormalRV.System.NaiveSchedule
FormalRV/System/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`.
Realizes the plan: 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
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 `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.NaiveUpperBound
FormalRV/System/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),
and the two are connected numerically in `ScheduleBounds.naive_opcount_eq_three_toff` /
`verified_toff_le_reported`. `ScheduleBounds.resource_bracket` brackets the lower bound
(`ScheduleLowerBound`) and this upper bound around one schedule's workload.
Motivation (John, 2026-06-02). 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 (John, 2026-06-02, after the ancilla-rule discussion).
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 ≤ footprintTHE UPPER BOUND: for every problem size `k`, the naive schedule's peak qubit
demand is ≤ the static footprint. No matter how many Toffolis the circuit
has, the naive sequential schedule fits inside the footprint — so the
footprint is an achievable (feasible) 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).qubitsSpecialised to the naive estimate's own qubit footprint: peak demand stays
within `naiveEstimate.qubits` for all problem sizes.
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.
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.ParallelismVerification
FormalRV/System/ParallelismVerification.lean
FormalRV.System.ParallelismVerification — IS the system-level framework
powerful enough to express ALL parallelism and reason about its correctness?
John's question (2026-06-02): a lot happens in parallel — while logical qubit
A measures syndromes, qubit B does lattice surgery, the factory prepares magic
states — and MAXIMUM parallelism is allowed as long as the system invariants
hold. Is the framework powerful enough?
ANSWER (this file demonstrates it). qianxu's parallelism (paper read, App. B/E/F)
splits into exactly TWO classes, and the framework already 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.
SEMANTIC bridge: exclusivity (A) makes time-overlapping ops act on disjoint
atoms — so their physical circuits COMMUTE — so the concurrent schedule equals
some sequential order, and per-operation correctness (the PPM / `CliffordConj`
layer) lifts to the whole parallel run (§C).
EXTENSIBILITY (the open-ended power): 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 = PPM layer; the bridge links them via disjointness ⇒ commutation).
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 — they all commute, so the concurrent run sequentializes and per-op
correctness lifts to the whole parallel schedule.
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.ReactionLimitedRuntime
FormalRV/System/ReactionLimitedRuntime.lean
FormalRV.System.ReactionLimitedRuntime — SELF-AUDIT finding #1: our "2.5× time
gap" is mostly a MODELLING artefact (d-cycle vs reaction-limited), and the real
residual assumption is DECODER THROUGHPUT.
## What the audit found
Our `surfaceModel.tauToff = d` charges `d` code cycles (= 27 µs at d=27, 1 µs
cycle) PER logical Toffoli, executed SEQUENTIALLY. But GE2021 runs
REACTION-LIMITED (notes/gidney-ekera-2021.md; paper §"reaction time 10 µs"): the
next Toffoli starts after the DECODE+feed-forward (one reaction time, 10 µs),
NOT after `d` full cycles. So:
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)
The 20.25/7.5 ≈ 2.7× "gap" we reported is EXACTLY the reaction-time (10 µs) vs
d-cycle (27 µs) ratio. With the CORRECT (reaction-limited) cost the framework
REPRODUCES GE2021's ~7.5 h — there is no unexplained algorithmic speed-up.
## The REAL residual assumption (the larger gap to watch)
Reaction-limited execution SECRETLY ASSUMES the classical decoder returns a
logical result within ONE reaction time (10 µs) for EVERY logical qubit, every
step. Across ~6200 patches each emitting a syndrome every 1 µs, this is a
~6 Gsyndrome/s real-time DECODING load. If decoding cannot keep up, the
reaction time GROWS (Fowler/Terhal backlog) and the runtime degrades toward — or
past — our d-cycle ceiling. That classical-decoding throughput is NOT in the
20 M qubit budget and NOT modelled by our `decoderInv` (which only bounds a
single decode's latency). See `ReactionLimitedRuntime` §3 + the audit report.
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_tenthsUs*The assumption, stated**: reaction-limited 7.5 h is valid IFF the decoder
sustains `realtimeDecodeLoad` within `reactionTime`. Otherwise the effective
reaction time grows and the runtime degrades toward the d-cycle ceiling (or
worse, on backlog). This is the honest residue our 7.5-h reproduction rests
on — flagged, not hidden.
FormalRV.System.ResourceAuditGaps
FormalRV/System/ResourceAuditGaps.lean
FormalRV.System.ResourceAuditGaps — the SELF-AUDIT's uncounted-cost findings,
encoded so each omission becomes a NAMED, CHECKABLE fact instead of a footnote.
An 8-dimension adversarial audit (2026-06-02) found NO genuine cheats — the
headline numbers are all labelled/derived — but SEVEN incomplete considerations,
three of which can push the TRUE cost above our admitted 2.5×. This module
encodes those three so they cannot hide:
GAP 1 decoder THROUGHPUT (not just latency) — the missing `load ≤ capacity`.
GAP 2 critical-path floor (~4 min) is ~100× below GE2021's 7.5 h ⇒ the run is
reaction-limited at the Toffoli COUNT, not the DEPTH; serial lookups
could add to the floor (the 7.5 h could be optimistic).
GAP 3 magic-state factory undersize (~17×) + uncounted delivery transport.
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; it 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.
theoremdecoder_lanes_not_in_qubit_budget
theorem decoder_lanes_not_in_qubit_budget (nLanes : Nat) :
(decoderThroughputInv 6200 10 nLanes).check =
(fun _ => decoderThroughputOk 6200 10 nLanes)The decoder fabric is a CLASSICAL resource that the 20 M qubit budget does not
contain: the throughput invariant constrains `nLanes`, a co-processor count.
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.
theoremdemo_factory_undersized_vs_ge2021
theorem demo_factory_undersized_vs_ge2021 :
100_000 * 17 ≤ 1_700_000Our `demoFactory` charges 100 k qubits/copy; GE2021's distillation budget (~7 %
of 20 M ≈ 1.4 M over ~6 CCZ factories) implies ~1.7 M qubits/factory — our demo
is ~17× too small for that slice.
defmagicDeliveryCyclesPerState
def magicDeliveryCyclesPerState (d : Nat) : Nat
Magic-state DELIVERY (factory-zone boundary → target data patch via lattice
surgery) costs ~d cycles PER STATE and competes for the routing area — and is
in NEITHER `cyclesPerMagic` (production only) NOR any invariant. At d=27 that
is ≥ 27 extra cycles per magic state, uncounted.
theoremge2021_magic_delivery_uncounted
theorem ge2021_magic_delivery_uncounted : magicDeliveryCyclesPerState 27 = 27
theoremaudit_verdict_no_cheat_only_omission
theorem audit_verdict_no_cheat_only_omission :
-- the 2.5x is the labelled d-cycle/reaction ratio (not a hidden factor):
ReactionLimitedRuntime.dCycleRuntime 2_700_000_000 27 10
= 729_000_000_000
-- and the decoder load is now bound-able (GAP 1 closed as an invariant):
∧ decoderThroughputOk 6200 10 62_000 = true*No fabricated fudge factor**: the headline time figures are exactly the cost
model applied to cited inputs. `ReactionLimitedRuntime` proves the 2.5× is the
27 µs/10 µs ratio; this module shows the residual risk is OMISSION (decoder
throughput, serial lookups, factory/transport), each now a named fact.
FormalRV.System.RoutingResourceModel
FormalRV/System/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 good, general cost primitive — it is the SIZE of the reserved routing
region — provided it is the size of a footprint that actually participates in the
exclusivity and capacity invariants (so one cannot claim routing cost without reserving the
resources).
## 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 number of resources the routing region
reserves. Kept as the user wants, but now it is the size of a footprint that is exclusivity-
and capacity-checked (see `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.routingQubitsThe routing cost is realized in the footprint: the footprint has exactly
`operands + routingQubits` resources. So `routingQubits` cannot be claimed without reserving
(and hence exclusivity- and capacity-checking) those resources.
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.lengthA surface-code PPM's `routingQubits` is exactly the number of ancilla-path resources it
reserves — the general routing cost matches the paper's ancilla-region occupancy.
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 / latency / throughput are SHARED.** Changing an operation's routing kind
(transport ↔ surgery) does NOT change how it conflicts — so neutral-atom and surface-code
routing are treated identically for scheduling. This is the part the two architectures share.
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.ScheduleAdvance
FormalRV/System/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 (`NaiveBaselineCost`) 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.** No amount of factory parallelism can drive the device spacetime below the
magic-state floor `Q·T ≥ K·fq·prod` (`ScheduleLowerBound.magic_spacetime_floor`). The paper
already sits ~7× above this 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. Here we record that the parallel-supply runtime stays at or
above the floor's implied minimum.
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`. 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.ScheduleBounds
FormalRV/System/ScheduleBounds.lean
FormalRV.System.ScheduleBounds — the UNIFICATION of the two bound efforts: bracket ONE resource
on ONE schedule (`DSchedule`).
The two subsystems bounded resources on disjoint data models:
UPPER bound (main): `NaiveUpperBound.naivePeak_le_footprint` — a sequential schedule's peak
qubit demand ≤ its static footprint, on `ResourceEstimate`.
LOWER bound (this branch): `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 main's
`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.
theoremnaive_opcount_eq_three_toff
theorem naive_opcount_eq_three_toff : NaiveSchedule.rsa2048_opCount = 3 * 2622824448
The `DSchedule` op count (`3·K`, prepare→teleport→decode per Toffoli) vs the verified Toffoli
budget `K`.
theoremverified_toff_le_reported
theorem verified_toff_le_reported : (2622824448 : Nat) ≤ 2700000000
The VERIFIED Toffoli budget (`2 622 824 448`, used by `NaiveSchedule`/`ScheduleLowerBound`) is
below the GE2021 REPORTED Toffoli count (`≈ 2.7×10⁹`, charged by `NaiveUpperBound`); the two
naive efforts are about the same computation, denominated from different sources.
FormalRV.System.ScheduleInvariantsExplicit
FormalRV/System/ScheduleInvariantsExplicit.lean
FormalRV.Framework.ScheduleInvariantsExplicit — general
decidable checkers for the four system-level invariants
exactly as stated in qianxu (Cain–Xu et al. 2026) Sec.
SysLayer / our `Framework/SysLayer.lean`.
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 Sec. SysLayer)
**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: for every pair (atom claimed by a syscall, zone), check
atom is in zone OR atom is not in zone. Linear-in-atoms.
I2: pairwise over syscalls (O(n²)) — for each pair, if time
intervals overlap, check atom-list disjointness.
I3: per-syscall check on `feedback`/`route` syscalls.
I4: per-window check over the n+1 distinct start-times
formed by `magicReq` begin times. Only O(n²) windows to
enumerate (any window not aligned with a magicReq begin
has the same count as the nearest aligned one).
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 distinct begin-times in the
schedule. Any in-between time has the same active set as
the nearest preceding begin-time, so this is sufficient.
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.
(Previously this check existed only at the non-decidable
`Architecture.latency_ok : Prop` level; this is the decidable
counterpart.)
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`.
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 now lives in the
architecture (`ZonedArch.t_react_us`), so a decode slower than the budget is rejected here — it
no longer needs the separate `decoder_react_ok` call.
FormalRV.System.ScheduleLowerBound
FormalRV/System/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 — 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`.
theoremrsa2048_floor_uses_budget
theorem rsa2048_floor_uses_budget :
rsa2048_floor_qubit_us = rsa2048_toffoli_budget * (2565 * 12000)The floor is denominated against the canonical Toffoli budget.
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×.**
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.StabilizerScheduleVerify
FormalRV/System/StabilizerScheduleVerify.lean
FormalRV.System.StabilizerScheduleVerify — let the USER specify their own
stabilizer-measurement schedule (the CNOT ordering per check), and VERIFY ALL
schedules at once.
A syndrome round measures an X-check on support S by: ancilla in |+⟩, `CX anc→s`
for each `s ∈ S` in SOME ORDER, measure ancilla in X (dually Z). The user picks
the order (the stabilizer schedule). KEY FACT: the CNOTs share the ancilla as
common control, so they COMMUTE, and the measured operator depends only on the SET
S — NOT the order. Hence the framework verifies EVERY schedule uniformly: any two
orderings that are permutations of each other measure the IDENTICAL stabilizer.
This makes "verify all scheduling" a theorem (`scheduledCheckOp_perm_invariant`),
parametric over the user's `List Nat` order. `StimEmit.xCheckBlock` already takes
the support as an ordered `List Nat`, so a user emits their schedule directly; the
theorem certifies it measures the right stabilizer regardless of the order they
chose.
No `sorry`, no `axiom`.
abbrevCNOTOrder
abbrev CNOTOrder
A user-supplied CNOT ordering for one check: the order the ancilla is coupled to
its support qubits. ANY `List Nat`.
defscheduledSupport
def scheduledSupport (order : CNOTOrder) (n : Nat) : BoolVec
The support a scheduled measurement actually produces: the SET of coupled qubits
over `n` qubits — order-agnostic by construction.
theoremscheduledSupport_perm_invariant
theorem scheduledSupport_perm_invariant (order order' : CNOTOrder) (n : Nat)
(h : order.Perm order') : scheduledSupport order n = scheduledSupport order' n*All CNOT orderings produce the same measured support.** Two schedules that
are permutations of each other (same coupled set, any order) yield the IDENTICAL
indicator — the stabilizer support is invariant under the user's scheduling.
defscheduledCheckOp
def scheduledCheckOp (color : ZXColor) (order : CNOTOrder) (n : Nat) : PauliString
The Pauli a scheduled check measures: a Z-check measures `zRow` of its coupled
support, an X-check `xRow`.
theoremscheduledCheckOp_perm_invariant
theorem scheduledCheckOp_perm_invariant (color : ZXColor) (order order' : CNOTOrder)
(n : Nat) (h : order.Perm order') :
scheduledCheckOp color order n = scheduledCheckOp color order' n*VERIFY ALL SCHEDULING.** For ANY user-chosen CNOT orderings that permute the
same coupled set, a check measures the IDENTICAL stabilizer — so every stabilizer
schedule is correct, and the framework certifies them all uniformly.
example(example)
example : scheduledCheckOp ZXColor.X [0, 1, 2] 3 = scheduledCheckOp ZXColor.X [2, 0, 1] 3
An X-check on {0,1,2} measured in order [0,1,2] vs [2,0,1] (a user reschedule)
measures the SAME stabilizer.
example(example)
example : scheduledCheckOp ZXColor.X [2, 0, 1] 3 = xRow [true, true, true]
…and both equal the `xRow` of the full support {0,1,2}.
example(example)
example : scheduledCheckOp ZXColor.Z [0, 3, 9] 10 = scheduledCheckOp ZXColor.Z [9, 3, 0] 10
A Z-check rescheduled [0,3,9] → [9,3,0] measures the same stabilizer (10 qubits).
FormalRV.System.SyndromeMeasurementLatency
FormalRV/System/SyndromeMeasurementLatency.lean
FormalRV.System.SyndromeMeasurementLatency — syndrome-extraction overhead made
explicit and HARDWARE-LATENCY-DRIVEN.
Four subtle points the user flagged, addressed as verified facts:
(1) EXTRA ANCILLA: every surface patch carries one syndrome-measure ancilla per
stabilizer — `(n−1)` for an `[[n,1,d]]` patch — counted per patch.
(2) FIXED-SCHEDULE COMPILED CIRCUIT: the per-check syndrome round is the explicit
`RX/CX…/MX` (X) and `R/CX…/M` (Z) circuit of `StimEmit.surgeryToStim`; one
round costs (gate-layers · t_gate + t_measure + t_reset).
(3) ALWAYS-ON, EVEN IDLE: syndrome extraction runs every code cycle on EVERY
logical qubit for the WHOLE computation — an idle patch still measures all its
stabilizers every round. So the physical syndrome-measurement count scales
with (all qubits) × (total cycles), not with active operations.
(4) MEASUREMENT-LATENCY-DRIVEN TIME: the surface-code CYCLE time is a function of
the qubit-measurement latency `t_measure`; changing it immediately changes the
verified runtime (and the always-on syndrome cost).
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.
theoremidle_patch_still_measures
theorem idle_patch_still_measures (d nToff : Nat) :
totalPhysicalSyndromeMeas 1 d nToff
= syndromeAncillaPerPatch d * totalSyndromeRounds nToff d*IDLE QUBITS ARE NOT FREE.** A patch with ZERO Toffolis of its own still
contributes `(n−1) · (n_toff · d)` physical syndrome measurements — the full
computation duration of always-on extraction. (Here: its share is exactly the
per-patch term, independent of how many of the global Toffolis touch it.)
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.SystemChecker
FormalRV/System/SystemChecker.lean
FormalRV.Framework.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.
## What this file is NOT
This file does NOT introduce a strengthened replacement
checker — that is a follow-up tick. Each gap is documented
with a precise specification of what a fix would look like.
Counterexamples that the current checker correctly rejects
also live here (positive control).
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 = trueexample(example)
example : True
Documented limitation: under the current `ArchZone`
semantics, `capacity_per_cycle_ok` is redundant given
`capacity_in_arch_ok ∧ exclusivity_ok`. A proof would
need a List-disjointness lemma and a zone-disjointness
hypothesis that the framework does not currently expose.
Leaving this as a TODO does not weaken the checker, only
its presentation.
defpositive_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.SystemInvariantExamples
FormalRV/System/SystemInvariantExamples.lean
FormalRV.System.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, and this file is part of the umbrella
`lake build` (imported by `FormalRV/System.lean`), so the verdicts are regression-checked by CI.
The matching emitted `DEVICE-PROGRAM` text is printed by the standalone demo
`FormalRV/Codegen/SysCallEmitDemo.lean` (run with `lake env lean …`).
Workflow: build a `Schedule` (physical ops + system calls) → CHECK with
`ScheduleInv.all_invariants_ok` → emit. Since `ZonedArch` now carries `t_react_us`, 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 parameters: qianxu's CCZ factory makes ≤ 1 magic state per 12 000 µs.
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
It genuinely overlaps in time (real parallelism): both PPMs' joint gates run in `[1,2)`.
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 now 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.SystemInvariantStrengthening
FormalRV/System/SystemInvariantStrengthening.lean
FormalRV.Framework.SystemInvariantStrengthening — first
repair step after the system-checker review.
## Background
`Framework/SystemChecker.lean` documented six abstraction
bugs in the existing strengthened bundle
(`all_invariants_with_factory_ports_ok` in
`Framework/LatticeSurgeryPPMContract.lean`). Each bug is paired
with a tiny counterexample schedule whose acceptance is proven
by `native_decide`.
This file fixes the two highest-impact bugs:
A. **Operation-capacity gap.** The existing
`capacity_per_cycle_ok` bounds per-cycle SITE counts using
`ArchZone.capacity = site_hi - site_lo`. Under
`exclusivity_ok`, this is redundant (review §9) — and it
does NOT bound the number of simultaneous OPERATIONS the
hardware can sustain (e.g., "the device supports at most
1 parallel Gate2q regardless of how many sites are
available").
Fix: add an `OperationCapacityModel` carrying independent
per-kind caps (`max_gate2q_active`, `max_decode_active`,
…) and a sampled active-count check
`operation_capacity_ok`.
B. **Feedback-after-decode causal gap.** The existing
`decoder_react_ok` bounds `DecodeSyndrome` DURATION only.
It does NOT enforce that a `PauliFrameUpdate cid` fires
AFTER the matching `DecodeSyndrome cid`.
Fix: add `feedback_after_decode_ok` requiring every
`PauliFrameUpdate cid` to find some `DecodeSyndrome cid`
whose `end_us ≤ begin_us` of the feedback.
Both fixes compose into a new sibling bundle
`all_invariants_strict_ok` which is STRICTLY STRONGER than
`all_invariants_with_factory_ports_ok`: the latter accepts
schedules that the former rejects. Both old bundles remain
available unchanged.
## What is NOT fixed in this tick
`target_pauli` ignored by the topology compiler
(review §3, `topology_compiler_ignores_target_pauli`).
Routing-lane / coupler exclusivity for `Gate2q`
(review §5, `routing_lane_violator_accepted`).
`RequestFreshAncilla` freshness/reset lifecycle
(review §6, `freshness_use_before_reset_accepted`,
`freshness_reuse_without_reset_accepted`).
`SiteId` / `FactoryPortId` type-level partition
(review §7, `site_id_conflation_accepted`).
Factory causal-supply prefix
(review §8, `magic_no_startup_prefix_accepted`).
Optional `slot_capacity_ok` per-zone slot cap — deferred;
see §3 below for the exact missing
`ArchZone`/`ZonedArch` accessor that would unblock it.
All five remaining gaps are preserved as regression-test
counterexamples in the review file; this file's §10 cross-
references them.
## 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*TODO 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*TODO regression**: the strict bundle still accepts
`freshness_use_before_reset` (no lifecycle state machine
yet).
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*TODO 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?
deffindAncillaZone
def findAncillaZone
(model : AncillaModel) (zone_id : Nat) : Option AncillaZoneSpecFind the spec for a given `target_zone` id (the first
match).
deffindFreeOrDirtyInZone
def findFreeOrDirtyInZone
(state : List (Nat × SiteLifecycle)) (z : AncillaZoneSpec) : Option NatFind the smallest site in zone `z`'s range whose current
lifecycle is NOT `Live` (i.e., `Free` or `Dirty`). This
is the "next free site" rule.
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 zone, id 1, sites
`[100, 200)`. Matches `surgery_arch`'s Ancilla zone and
the compilers' `RequestFreshAncilla 1` convention.
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 1` calls with
only one Measure available — after the first allocation,
the model picks the next-smallest Free/Dirty site for
the second allocation, so this is actually allowed
(different sites). But if the zone exhausts, the second
Request fails. We exhibit a 1-site sub-model to force
rejection.
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, 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.ZoneBudget
FormalRV/System/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 cntA zone's capacity in the built architecture is exactly its user-set count.
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).totalIncreasing ANY zone's budget increases the total (monotone, parametric) — more
qubits per zone ⇒ a larger machine, as the user sets it.