Download runtime/quantum/FORMAL_ARCHITECTURE.md from Snapkitty/carry-agent: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/Snapkitty/carry-agent/resolve/main/runtime/quantum/FORMAL_ARCHITECTURE.md
- Command line
-
hf download hf://Snapkitty/carry-agent/runtime/quantum/FORMAL_ARCHITECTURE.md
-
curl -L -o FORMAL_ARCHITECTURE.md https://huggingface.co/Snapkitty/carry-agent/resolve/main/runtime/quantum/FORMAL_ARCHITECTURE.md
Carry Quantum: Formal Architecture
Goal: Proof-carrying execution. The formal model is the source of truth.
Date: 2026-08-21
Layer Map
FORMAL SEMANTICS (Source of Truth)
ββββββββββββββββββββββββββββββββββββββββββββ
β Agda β
β dependent types / illegal states β
β unrepresentable at the type level β
ββββββββββββββββββ¬ββββββββββββββββββββββββββ
β shared definitions
βΌ
ββββββββββββββββββββββββββββββββββββββββββββ
β Lean 4 β
β theorem obligations / proof engine β
β normalization, purity, cycles, β
β absorption, DAG, bounds, ownership β
ββββββββββββββββββ¬ββββββββββββββββββββββββββ
β verified IR / spec
βΌ
RUNTIME CONTRACT
β
ββββββββββββββββββ΄βββββββββββββββββ
β β
βΌ βΌ
F# reference backend Rust minimal runtime
executable semantics low-level substrate
conformance corpus native / WASM / embedded
β β
βββββββββββββ conformance βββββββββ
test suite
One specification, two proof perspectives, one reference interpreter, one execution substrate.
Agda and Lean are not two implementations β they are two views over one mathematical core.
Four-Class Taxonomy
Every formal statement in this system belongs to exactly one class.
AXIOM mathematical assumption β asserted, not proved
DEFINITION what the machine means β gives semantic content
INVARIANT property preserved by execution β proved by induction
REFINEMENT proof that implementation matches semantics β closes the loop
Calling everything an "invariant" obscures which facts are load-bearing assumptions, which are semantic choices, and which are correctness guarantees. The classes below apply this taxonomy to all seven properties from the initial extraction.
Agda: Dependent-Type Specification
The goal in Agda is to make illegal states unrepresentable, not to test them afterward.
FSM State Type
module CarryQuantum.FSM where
data FSMState : Set where
Init : FSMState
Prepare : FSMState
Entangle : FSMState
Compute : FSMState
Measure : FSMState
Verify : FSMState
Commit : FSMState
Halted : FSMState
CycleLimit : FSMState
Allowed Transition β Encoded in the Type
Rather than a runtime predicate, make the allowed edge relation a type index.
A Transition s s' value can only be constructed when (s, s') is a legal edge.
data Transition : FSMState β FSMState β Set where
T-Init-Prepare : Transition Init Prepare
T-Prep-Entangle : Transition Prepare Entangle
T-Ent-Compute : Transition Entangle Compute
T-Comp-Measure : Transition Compute Measure
T-Meas-Verify : Transition Measure Verify
T-Veri-Commit : Transition Verify Commit
T-Comm-Prepare : Transition Commit Prepare -- loop
T-Comm-Commit : Transition Commit Commit -- terminal
T-Any-Halted : β {s} β Transition s Halted -- emergency
A value of type Transition s s' is a machine-checked proof that (s, s') is allowed.
There is no runtime check β an illegal transition cannot be typed.
Step Function β INV-4 and INV-5 by Construction
record FSM : Set where
field
state : FSMState
cycle : β
max-cycle : β
bounded : cycle β€ max-cycle
data StepResult : Set where
ok : FSM β StepResult
error : String β StepResult
-- Terminal states cannot produce ok transitions
data Terminal : FSMState β Set where
T-Halted : Terminal Halted
T-CycleLimit : Terminal CycleLimit
step : FSM β (s' : FSMState) β Transition (FSM.state fsm) s' β StepResult
This encodes the refinement theorem directly:
step f a = ok f' β AllowedTransition f.state f'.state
is not a theorem to prove β it is a type guarantee. step only accepts a
Transition witness, so ok can only be produced for allowed edges.
The terminal absorption invariant (INV-5) becomes:
There is no value of type
Transition Halted s'for anys' β Halted.
Check: T-Any-Halted produces Transition s Halted β arriving at Halted.
No constructor produces Transition Halted s' for non-Halted s' β leaving Halted is
unrepresentable.
Lean 4: Proof Engine
Lean proves the semantic content of the definitions. It does not redefine the FSM β it imports the Agda definitions (or mirrors them exactly) and proves the theorem obligations.
Four-Class Breakdown
AXIOMS
-- AX-1: Complex arithmetic is sound (we trust Lean's β library)
-- AX-2: IEEE 754 f64 is a sufficient approximation for simulation purposes
-- AX-3: Random measurement outcomes are sampled from the Born distribution
-- (randomness is external; we prove properties conditioned on valid samples)
These are not proved. They are stated explicitly so the proof chain is honest.
DEFINITIONS
namespace CarryQuantum
-- DEF-1: Normalized state
def normalized {n : β} (Ο : Fin (2^n) β β) : Prop :=
β i, Complex.normSq (Ο i) = 1
-- DEF-2: Allowed transition (mirrors Agda, used for statement of refinement theorems)
def AllowedTransition : QFSMState β QFSMState β Prop
| .Init, .Prepare => True
| .Prepare, .Entangle => True
| .Entangle, .Compute => True
| .Compute, .Measure => True
| .Measure, .Verify => True
| .Verify, .Commit => True
| .Commit, .Prepare => True
| .Commit, .Commit => True
| _, .Halted => True
| _, _ => False
-- DEF-3: Terminal FSM state
def Terminal : QFSMState β Prop
| .Halted => True
| .CycleLimit => True
| _ => False
-- DEF-4: Unitary gate (norm-preserving linear map)
def IsUnitary {n : β} (U : (Fin (2^n) β β) β (Fin (2^n) β β)) : Prop :=
β Ο, normalized Ο β normalized (U Ο)
-- DEF-5: Agent ownership disjointness
def OwnershipDisjoint (a b : Finset β) : Prop := Disjoint a b
end CarryQuantum
INVARIANTS
namespace CarryQuantum.Invariants
-- INV-1: Normalization is preserved by unitary gate application
theorem gate_preserves_norm
{n : β} (Ο : Fin (2^n) β β) (U : _)
(h_norm : normalized Ο)
(h_unit : IsUnitary U) :
normalized (U Ο) :=
h_unit Ο h_norm
-- INV-2: Purity is bounded in (0, 1]
-- OPEN: requires Ο βͺ° 0 β§ Tr(Ο) = 1 β pending Mathlib matrix assembly
theorem purity_bounded : sorry := sorry
-- INV-3: Cycle counter is strictly monotone
theorem cycle_monotone (fsm : QFSM)
(h_valid : AllowedTransition fsm.state s')
(h_limit : fsm.cycle < fsm.max_cycle) :
β fsm' : QFSM,
fsm'.state = s' β§
fsm'.cycle = fsm.cycle + 1 β§
fsm'.cycle β€ fsm'.max_cycle := by
exact β¨β¨s', fsm.cycle + 1, fsm.max_cycle, by omegaβ©, rfl, rfl, by omegaβ©
-- INV-4: Transition DAG confinement
-- NOTE: In the Agda layer this is a type guarantee, not a theorem.
-- In Lean it is a semantic consequence of AllowedTransition.
-- The proof obligation is that the runtime (F# / Rust) only calls step with
-- a valid AllowedTransition witness (see REFINEMENT section).
-- INV-5: Terminal states are absorbing
theorem terminal_no_step (s : QFSMState)
(h_term : Terminal s) :
β s', Β¬ AllowedTransition s s' β¨ s' = QFSMState.Halted := by
intro s'
cases s <;> simp [Terminal, AllowedTransition] at *
-- INV-6: Gate targets are in-bounds and distinct
def targets_valid (n : β) (targets : List β) : Prop :=
targets.Nodup β§ β t β targets, t < n
-- INV-7: All agent qubit ownership sets are pairwise disjoint
def AllAgentsDisjoint (owners : List (Finset β)) : Prop :=
β i j (hi : i < owners.length) (hj : j < owners.length),
i β j β Disjoint (owners[i]'hi) (owners[j]'hj)
end CarryQuantum.Invariants
REFINEMENT THEOREMS
These are the class the original INVARIANTS.md was missing. They close the gap between the formal spec and the running implementation.
namespace CarryQuantum.Refinement
-- REF-1: F# / Rust `transition` only succeeds for allowed edges
-- (This is stated as a specification obligation on the runtime implementation)
axiom rust_transition_correct :
β (fsm : QFSM) (s' : QFSMState),
RustRuntime.transition fsm s' = .ok fsm' β
AllowedTransition fsm.state s'
-- REF-2: F# / Rust `transition` fails on terminal states
axiom rust_terminal_halts :
β (fsm : QFSM) (s' : QFSMState),
Terminal fsm.state β
RustRuntime.transition fsm s' = .err "FSM_TERMINAL"
-- REF-3: F# apply_gate preserves normalization
axiom fsharp_gate_norm :
β (Ο : StateVector) (g : Gate),
normalized Ο.amplitudes β
normalized (FSharpRuntime.apply_gate g Ο).amplitudes
-- These axioms become theorems once the conformance test suite is built
-- and the F# reference interpreter is verified against it.
-- REF-1 and REF-2 are discharged by the conformance corpus.
-- REF-3 is discharged by numeric verification of each gate matrix.
end CarryQuantum.Refinement
F# Reference Backend
F# is the executable semantic reference. It is not the production runtime β it is the thing Rust must agree with on all conformance inputs.
module CarryQuantum.Reference
type FSMState =
| Init | Prepare | Entangle | Compute
| Measure | Verify | Commit | Halted | CycleLimit
type StepError = InvalidTransition | TerminalState | CycleLimitReached
let allowedTransition (s : FSMState) (s' : FSMState) : bool =
match s, s' with
| Init, Prepare -> true
| Prepare, Entangle -> true
| Entangle, Compute -> true
| Compute, Measure -> true
| Measure, Verify -> true
| Verify, Commit -> true
| Commit, Prepare -> true
| Commit, Commit -> true
| _, Halted -> true
| _, _ -> false
let isTerminal = function Halted | CycleLimit -> true | _ -> false
// step : FSM β FSMState β Result<FSM, StepError>
// This is the executable version of the Agda `step` β same semantics, runnable.
let step (fsm : FSM) (target : FSMState) : Result<FSM, StepError> =
if isTerminal fsm.State then
Error TerminalState // REF-2
elif fsm.Cycle >= fsm.MaxCycle then
Ok { fsm with State = CycleLimit }
elif not (allowedTransition fsm.State target) then
Error InvalidTransition // REF-1
else
Ok { fsm with State = target; Cycle = fsm.Cycle + 1 }
The conformance test suite runs F# step and Rust transition on the same
inputs and asserts identical outputs. Any divergence is a Rust bug, not a proof gap.
Rust: Minimal Runtime
Rust is not where the mathematics lives. It is an implementation of the formally specified machine, constrained to:
minimal state
minimal allocator
minimal scheduler
minimal numerical kernel
minimal FFI
minimal error model
The single change required by the invariant extraction (INV-5 bug):
// carry-agent/runtime/quantum/fsm.rs
pub fn transition(&mut self, target: QuantumFSMState, ...) -> Result<...> {
// REFINEMENT REF-2: terminal states are absorbing
if matches!(self.state, QuantumFSMState::Halted | QuantumFSMState::CycleLimit) {
return Err(format!("FSM_TERMINAL: cannot transition from {:?}", self.state));
}
// ... rest unchanged
}
Execution Chain
Agda (illegal states unrepresentable)
β
β shared definitions
βΌ
Lean 4 (INV-1,2,3,4,5,6,7 + REF-1,2,3 proven)
β
β verified spec / IR
βΌ
F# reference interpreter (executable semantics)
β
β conformance corpus
βΌ
Rust minimal runtime (conformance-tested implementation)
β
βΌ
native / WASM / embedded target
Open Obligations
| ID | Class | Description | Path to closure |
|---|---|---|---|
| AX-3 | AXIOM | Born rule randomness is external | Accept as axiom; document explicitly |
| INV-2 | INVARIANT | 0 < Tr(ΟΒ²) β€ 1 |
Mathlib Matrix.PosSemidef + Cauchy-Schwarz |
| INV-1 full | INVARIANT | Replace IsUnitary hypothesis with proof from gate matrices |
Prove each gate matrix is unitary in Lean |
| REF-1 | REFINEMENT | Rust transition only accepts allowed edges |
Conformance corpus + property test |
| REF-2 | REFINEMENT | Rust transition fails on terminal states |
Fix INV-5 bug first, then property test |
| REF-3 | REFINEMENT | F# apply_gate preserves normalization |
Numeric verification of each gate matrix |
| Agda-Lean bridge | ARCHITECTURE | Shared definition import so neither diverges | Decide: shared file or auto-generated Lean from Agda |